1. # Load necessary libraries
  2. library(httr)
  3. library(jsonlite)
  4. library(dplyr)
  5. library(openxlsx)
  6. # Store your API key in a variable
  7. api_key <- "YOUR_API_KEY_HERE"
  8. get_adverse_events <- function(drug_name, skip=0) {
  9. # Define the URL for the FDA API request
  10. url <- paste0("https://api.fda.gov/drug/event.json?search=patient.drug.medicinalproduct:",
  11. URLencode(drug_name), "+AND+receivedate:[20220101+TO+20220105]&limit=100&skip=", skip)
  12. # Add the API key to the request headers
  13. headers <- add_headers(Authorization = paste("Bearer", api_key))
  14. response <- GET(url, headers) # Make a GET request to the FDA API with headers
  15. if (status_code(response) == 200) { # Check if the request was successful (status code 200)
  16. return(content(response, as="parsed")) # Return the response data as a parsed JSON object
  17. } else {
  18. return(NULL) # Return NULL if the request was not successful
  19. }
  20. }
  21. statins <- c("atorvastatin", "rosuvastatin", "simvastatin", "pravastatin", "lovastatin")
  22. # Vector of statin drugs to search for adverse events
  23. all_data <- data.frame() # Initialize an empty data frame to store all adverse event data
  24. for (statin in statins) { # Loop through each statin in the vector
  25. skip <- 0 # Initialize the skip parameter to 0 for pagination
  26. repeat { # Infinite loop to keep fetching data until no more results
  27. data <- get_adverse_events(statin, skip) # Get adverse events data for the current statin
  28. if (is.null(data) || !("results" %in% names(data))) { # Check if there is no data or no results
  29. break # Exit the loop if no more data
  30. }
  31. events <- data$results # Extract the events from the data
  32. for (i in seq_along(events)) { # Loop through each event in the results
  33. adverse_event <- data.frame(
  34. Drug = paste0(toupper(substring(statin, 1, 1)), substring(statin, 2)),
  35. Reaction = ifelse(is.null(events[[i]]$patient$reaction[[1]]$reactionmeddrapt), NA, events[[i]]$patient$reaction[[1]]$reactionmeddrapt),
  36. Outcome = ifelse(is.null(events[[i]]$patient$reaction[[1]]$reactionoutcome), NA, events[[i]]$patient$reaction[[1]]$reactionoutcome),
  37. Date = ifelse(is.null(events[[i]]$receivedate), NA, events[[i]]$receivedate),
  38. Age = ifelse(is.null(events[[i]]$patient$patientonsetage), NA, events[[i]]$patient$patientonsetage),
  39. Age_Unit = ifelse(is.null(events[[i]]$patient$patientonsetageunit), NA, events[[i]]$patient$patientonsetageunit),
  40. Gender = ifelse(is.null(events[[i]]$patient$patientsex), NA, events[[i]]$patient$patientsex)
  41. )
  42. all_data <- bind_rows(all_data, adverse_event) # Add the adverse event data to the data frame
  43. }
  44. skip <- skip + 100 # Increment the skip parameter to get the next set of results
  45. }
  46. }
  47. write.xlsx(all_data, "adverse_events_statins_r.xlsx", rowNames=FALSE) # Save the data frame to an Excel file