PMassicotte / gtrendsR

R functions to perform and display Google Trends queries
352 stars 112 forks source link

Indexing error in gtrends if either TOP or RISING has zero entries for related topics #423

Closed MalikStromberg closed 2 years ago

MalikStromberg commented 2 years ago

Hi there,

while using your great package intensively I recently encountert an error from gtrends. If there are either no related top topics or no related rising topics for the key word, the function throws the following error:

Error in start_top:end_top : NA/NaN argument

The error originates from create_related_topics_payload inside related_topics inside gtrendsR::gtrends. If there are no entries for any of "TOP" or "RISING", the indexing variables start_top or start_rising respectively cannot be reliably created. That is how they are created:

  start_top <- which(grepl("TOP", res))[1]
  start_rising <- which(grepl("RISING", res))[1]

In the course of the function the varaibles will be checked to be not of length 0, but not to be not NA. However, when creating the variables the indexing [1] at the end is responsible for the variable to be NA if either TOP or RISING is missing in res instead of numeric(0).

The error is a problem for my work since I am only interested in TOP related topics regardless of rising. If RISING is missing, the information on TOP gets lost through the error.

Here is a reproducing example:

gtrends(
    keyword = "London Mule",
    geo = "DE",
    time =  "2022-05-01 2022-06-15",
    gprop = "web"
)

The TOP related topics for this key word in this country and this time period are "Gin gin mule" and "Moscow mule", while there are no rising related topics (prove). This can also be seen when looking at res in the debugging mode. Unfortunately, the function throws an error.

Thanks in advance!!

PMassicotte commented 2 years ago

Looks like it is working for me:

library(gtrendsR)

gtrends(
  keyword = "London Mule",
  geo = "DE",
  time =  "2022-05-01 2022-06-15",
  gprop = "web"
)$related_topics
#>   subject related_topics        value geo     keyword category
#> 1     100            top Gin gin mule  DE London Mule        0
#> 2      35            top  Moscow mule  DE London Mule        0

Created on 2022-06-22 by the reprex package (v2.0.1)

MalikStromberg commented 2 years ago

I tried the github-version, now it works perfectly fine since the github-version checks for both length and NA of the mentioned index variables in extract_top_rising. I will use the github-version from now on, but it would be great to have that on cran at some point.

Thanks a lot for your response!