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