0

My goal is to automate fetching of trends data along with the extraction of "interest_over_time" from the lists.

Considering it a two-step problem:

  • Automating fetching of data based on a group of keywords

  • Extracting elements automatically in a methodical manner

I am not able to complete step 2.

Any ideas on how to get this done?

Step1 - Automating fetch of google trends data

library(gtrendsR)
a <- c("sony", "apple")

for (i in a) {
  name <- (paste(i, sep=""))
  assign(name, gtrends(keyword=i, time="now 1-H"))
  print(name)
}

Step2 - Extracting elements

sony[["interest_over_time"]]

instead of doing it like above manually, can I use for or some other function to automate this?

markus
  • 25,843
  • 5
  • 39
  • 58
  • It is not clear where "interest_over_time" comes from. It's not in your code – Omry Atia Apr 21 '19 at 15:16
  • The function `gtrendsR::gtrends()` returns a list of 7. `interest_over_time` is one of the 7 returned `data.frame` objects. –  Apr 21 '19 at 15:20

2 Answers2

0

You could read in with sapply. The data will be stored into list l.

library(gtrendsR)
l <- sapply(c("sony", "apple"), function(i) gtrends(keyword=i, time="now 1-H"))

Access the data with l[[1]] and l[[2]].

head(l[[1]])
#                  date hits keyword   geo gprop category
# 1 2019-04-21 09:14:00   74    sony world   web        0
# 2 2019-04-21 09:15:00   72    sony world   web        0
# 3 2019-04-21 09:16:00   75    sony world   web        0
# 4 2019-04-21 09:17:00   84    sony world   web        0
# 5 2019-04-21 09:18:00   78    sony world   web        0
# 6 2019-04-21 09:19:00   83    sony world   web        0

head(l[[2]])
# location hits keyword   geo gprop
# 1 Falkland Islands (Islas Malvinas)   NA    sony world   web
# 2            São Tomé & Príncipe   NA    sony world   web
# 3                        Seychelles   NA    sony world   web
# 4                 St. Kitts & Nevis   NA    sony world   web
# 5                         Hong Kong  100    sony world   web
# 6                             Nepal   84    sony world   web
jay.sf
  • 60,139
  • 8
  • 53
  • 110
0

Here are a couple of ways that I think will give you what you want.

library(gtrendsR)

a = c("sony","apple")

First Way: using base R

gtrends_interest <- function(keyword) gtrends(keyword = keyword, time = "now 1-H")[["interest_over_time"]]
trends_data <- do.call('rbind', lapply(a, gtrends_interest))

Second Way: using purrr

library(purrr)
trends_data2 <- a %>%
  map_df( ~ gtrends(keyword = ., time = "now 1-H")[["interest_over_time"]])

Both methods will return a data.frame with the interest_over_time from each element in a stacked.

I prefer the second since map() becomes very powerful once you get a hang of it.