首页 > 解决方案 > 有没有办法自动从两个或多个列表中提取元素?

问题描述

我的目标是自动获取趋势数据以及"interest_over_time"从列表中提取。

考虑它是一个两步问题:

我无法完成第 2 步。

关于如何完成这项工作的任何想法?

Step1 - 自动获取谷歌趋势数据

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 - 提取元素

sony[["interest_over_time"]]

我可以使用 for 或其他一些功能来自动执行此操作,而不是像上面那样手动操作吗?

标签: rlistextractgoogle-trends

解决方案


你可以用sapply. 数据将存储到 list 中l

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

l[[1]]使用和访问数据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

推荐阅读