1. library(httr)
  2. library(jsonlite)
  3. library(dplyr)
  4. # Function to get recall data from the FDA API
  5. get_recall_data <- function(product) {
  6. base_url <- "https://api.fda.gov/food/enforcement.json"
  7. params <- list(
  8. search = paste0('product_description:"', product, '"'),
  9. limit = 100
  10. )
  11. response <- GET(base_url, query = params)
  12. if (status_code(response) == 200) {
  13. data <- content(response, as = "parsed", type = "application/json")
  14. if ("results" %in% names(data)) {
  15. recall_data <- lapply(data$results, function(x) {
  16. data.frame(
  17. Product = product,
  18. Recall_Date = ifelse(is.null(x$recall_initiation_date), "N/A", x$recall_initiation_date),
  19. Reason = ifelse(is.null(x$reason_for_recall), "N/A", x$reason_for_recall),
  20. stringsAsFactors = FALSE
  21. )
  22. })
  23. return(do.call(rbind, recall_data))
  24. } else {
  25. print(paste("No results found for product", product))
  26. return(data.frame())
  27. }
  28. } else {
  29. print(paste("Error:", status_code(response), "for product", product))
  30. return(data.frame())
  31. }
  32. }
  33. # List of products to search for
  34. products <- c("Doritos", "Cheetos", "Lay's", "Pringles", "Ritz", "Oreo", "Snickers")
  35. # Initialize an empty data frame to store results
  36. all_results <- data.frame()
  37. # Loop through each product and get recall data
  38. for (product in products) {
  39. recall_data <- get_recall_data(product)
  40. all_results <- bind_rows(all_results, recall_data)
  41. }
  42. # Save the results to a CSV file
  43. write.csv(all_results, "popular_snacks_recall_data.csv", row.names = FALSE)
  44. print("Data has been exported to popular_snacks_recall_data.csv")