Skipping Error in a Loop of Google Trends requests

76 Views Asked by At

For my Bachelor Thesis I need to pull Google Trends Data for several Brands in different countries. As I am totally new to R a friend of mine helped me create the code for a loop, which does it automatically. After a while the error data must be a data frame, or other object coercible by fortify(), not a list appears and the loop stops. When checking with the google trends page itself i found out that there is not enough data to support the request.

My question now would be, if it is possible to continue the loop, regardless of the error and just "skip" the request responsible for the error.

I Already looked around in other threads but the try() appears not to work here or I did it wrong. Also I changed the low_search_volume = FALSEwhich is the default to TRUE, but that didn't change anything.

for (row in 1:nrow(my_data)) {
    country_code <- as.character(my_data[row, "Country_Code"])
    query <- as.character(my_data[row, "Brand"])
    trend <- gtrends(
      c(query),
      geo = country_code,
      category = 68,
      low_search_volume = TRUE,
      time = "all"
      )
    plot(trend)
    export <- trend[["interest_over_time"]]
    filepath <- paste(
      "C:\\Users\\konst\\Desktop\\Uni\\Bachelorarbeit\\R\\Ganzer Datensatz\\",
      query, "_", country_code,
      ".csv",
      sep = ""
       )
    write.csv(export, filepath)
  }

To reproduce the error use following list:

Brand       Country Code
Gucci       MA
Gucci       US
allsaints   MA
allsaints   US

The allsaints MA request should produce the error. Therefore, the allsaints US will not processed.

Thank you all in advance for your assistance.

Best wishes from Hamburg, Germany

0

There are 0 best solutions below