How can I skip failed iterations in a for loop in R?
So, I'm trying to collect data with the Meta Ads Library API using a for loop. Currently, I'm running the code as it follows:
for (i in 1:336){
id <- ids_fpa_vetor[i] # vector of page ids
query <- adlib_build_query (ad_reached_countries = 'BR',
search_page_ids = id,
ad_delivery_date_min = "2018-05-07",
ad_delivery_date_max = "2023-05-19",
fields = c("id", "ad_creation_time", "spend", "delivery_by_region", "demographic_distribution", "ad_creative_bodies", "ad_delivery_start_time", "ad_delivery_stop_time", "ad_snapshot_url", "impressions", "page_id", "page_name", "publisher_platforms"),
limit = 30000)
response <- adlib_get_paginated(query, max_gets = 100, token = token)
results <- as_tibble(response, censor_access_token = TRUE)
DataFrame <- rbind.fill(DataFrame, results)
}
For those who are not familiarized with the Meta Ads Library API, I'm basically:
declaring my search query around 336 unique page IDs;
getting a response from the API;
transforming this response in a tibble;
and, finally, binding this tibble to a pre-existing dataframe that has the variables that interest me.
However, I keep getting some errors because of some of the pages we're trying to gather data from. For instance, pages that do not have any data or that were deleted from Facebook, for instance, that would be hard to manually verify.
I want to tell my code to ignore these errors and move on to the next iteration — that is, to the next page — in my process. What could I do?
It's useful to say that I am using the Radlibrary package.
I'm sorry if I wasn't clear enough since this is the first time in which I try to handle errors in R :)
response <- try(adlib_get_paginated(...))