您可以使用lapply 遍历关键字列表并提取请求的元素,如下所示:
library(gtrendsR)
time <- "today+5-y"
channel <- "web"
keywords <- list("compare", "switch", "change")
trends <- setNames(lapply(keywords, function(x) gtrends(keyword=x,
gprop=channel, geo="AU", time=time, category=249)), keywords)
lapply(trends, `[[`, "interest_over_time")
#> $compare
#> date hits geo time keyword gprop category
#> 1 2015-04-26 25 AU today+5-y compare web 249
#> 2 2015-05-03 26 AU today+5-y compare web 249
#> 3 2015-05-10 41 AU today+5-y compare web 249
#> 4 2015-05-17 29 AU today+5-y compare web 249
#> 5 2015-05-24 32 AU today+5-y compare web 249
# ...
#> 260 2020-04-12 9 AU today+5-y compare web 249
#>
#> $switch
#> date hits geo time keyword gprop category
#> 1 2015-04-26 0 AU today+5-y switch web 249
#> 2 2015-05-03 0 AU today+5-y switch web 249
#> 3 2015-05-10 0 AU today+5-y switch web 249
#> 4 2015-05-17 0 AU today+5-y switch web 249
#> 5 2015-05-24 0 AU today+5-y switch web 249
# ...
#> 260 2020-04-12 0 AU today+5-y switch web 249
#>
#> $change
#> date hits geo time keyword gprop category
#> 1 2015-04-26 45 AU today+5-y change web 249
#> 2 2015-05-03 68 AU today+5-y change web 249
#> 3 2015-05-10 23 AU today+5-y change web 249
#> 4 2015-05-17 52 AU today+5-y change web 249
#> 5 2015-05-24 76 AU today+5-y change web 249
# ...
#> 260 2020-04-12 38 AU today+5-y change web 249
由reprex package (v0.3.0) 于 2020 年 4 月 20 日创建
编辑:
一旦将单个列表元素组合到 data.table、tibble 或 data.frame 中,进一步操作数据可能是最容易的。此处显示的是如何删除不需要的列的示例。要按关键字进行子集化,可以这样做,例如res[keyword=="compare"]
library(gtrendsR)
library(data.table)
time <- "today+5-y"
channel <- "web"
keywords <- list("compare", "switch", "change")
trends <- setNames(lapply(keywords, function(x) gtrends(keyword=x,
gprop=channel, geo="AU", time=time, category=249)), keywords)
res <- rbindlist(lapply(trends, `[[`, "interest_over_time"))
res[,-c("geo","category","time")]
#> date hits keyword gprop
#> 1: 2015-04-26 25 compare web
#> 2: 2015-05-03 26 compare web
#> 3: 2015-05-10 41 compare web
#> 4: 2015-05-17 29 compare web
#> 5: 2015-05-24 32 compare web
#> ---
#> 776: 2020-03-15 51 change web
#> 777: 2020-03-22 27 change web
#> 778: 2020-03-29 20 change web
#> 779: 2020-04-05 0 change web
#> 780: 2020-04-12 35 change web
由reprex package (v0.3.0) 于 2020 年 4 月 21 日创建