- library(httr)
- library(jsonlite)
- library(dplyr)
-
- # Function to get recall data from the FDA API
- get_recall_data <- function(product) {
- base_url <- "https://api.fda.gov/food/enforcement.json"
- params <- list(
- search = paste0('product_description:"', product, '"'),
- limit = 100
- )
-
- response <- GET(base_url, query = params)
-
- if (status_code(response) == 200) {
- data <- content(response, as = "parsed", type = "application/json")
-
- if ("results" %in% names(data)) {
- recall_data <- lapply(data$results, function(x) {
- data.frame(
- Product = product,
- Recall_Date = ifelse(is.null(x$recall_initiation_date), "N/A", x$recall_initiation_date),
- Reason = ifelse(is.null(x$reason_for_recall), "N/A", x$reason_for_recall),
- stringsAsFactors = FALSE
- )
- })
- return(do.call(rbind, recall_data))
- } else {
- print(paste("No results found for product", product))
- return(data.frame())
- }
- } else {
- print(paste("Error:", status_code(response), "for product", product))
- return(data.frame())
- }
- }
-
- # List of products to search for
- products <- c("Doritos", "Cheetos", "Lay's", "Pringles", "Ritz", "Oreo", "Snickers")
-
- # Initialize an empty data frame to store results
- all_results <- data.frame()
-
- # Loop through each product and get recall data
- for (product in products) {
- recall_data <- get_recall_data(product)
- all_results <- bind_rows(all_results, recall_data)
- }
-
- # Save the results to a CSV file
- write.csv(all_results, "popular_snacks_recall_data.csv", row.names = FALSE)
- print("Data has been exported to popular_snacks_recall_data.csv")