1

对 r 来说相对较新,我有一个单词列表,我想通过 gtrendsr 函数查看谷歌搜索命中,然后创建一个以日期为索引的小标题,每个单词的相关命中作为列,我正在努力使用 purr 中的地图函数执行此操作,

我开始尝试使用 for 循环,但有人告诉我尝试在 tidyverse 包中使用 map ,这就是我到目前为止所拥有的:


library(gtrendsr)

words = c('cruise', 'plane', 'car')
for (i in words) {
  rel_word_data = gtrends(i,geo= '', time = 'today 12-m')
  iot <- data.frame()
  iot[i] <- rel_word_data$interest_over_time$hits
}

我需要让 gtrends 函数一次取一个词,否则它会给出一个命中值,该值会根据其他词的流行度进行调整。所以基本上,我需要 gtrends 函数来运行列表中的第一个单词,获取 interest_over_time 部分中的 hits 列,并将其添加到包含每个单词的列和作为索引的日期的最终数据帧中。

我有点迷失在没有for循环的情况下如何做到这一点

4

2 回答 2

2

假设每个关键字的 gtrends 输出长度相同,您可以执行以下操作:

# Load packages
library(purrr)
library(gtrendsR)

# Generate a vector of keywords
words <- c('cruise', 'plane', 'car')

# Download data by iterating gtrends over the vector of keywords
# Extract the hits data and make it into a dataframe for each keyword
trends <- map(.x = words,
              ~ as.data.frame(gtrends(keyword = .x, time = 'now 1-H')$interest_over_time$hits)) %>%
    # Add the keywords as column names to the three dataframes
    map2(.x = .,
         .y = words,
         ~ set_names(.x, nm = .y)) %>%
    # Convert the list of three dataframes to a single dataframe
    map_dfc(~ data.frame(.x))

# Check data
head(trends)
#>   cruise plane car
#> 1     50    75  84
#> 2     51    74  83
#> 3    100    67  81
#> 4     46    76  83
#> 5     48    77  84
#> 6     43    75  82
str(trends)
#> 'data.frame':    59 obs. of  3 variables:
#>  $ cruise: int  50 51 100 46 48 43 48 53 43 50 ...
#>  $ plane : int  75 74 67 76 77 75 73 80 70 79 ...
#>  $ car   : int  84 83 81 83 84 82 84 87 85 85 ...

reprex 包(v0.3.0)于 2020-06-27 创建

于 2020-06-27T14:30:39.480 回答
2

您可以使用map将所有数据作为列表获取并用于reduce组合数据。

library(purrr)
library(gtrendsr)
library(dplyr)

map(words, ~gtrends(.x,geo= '', time = 'today 12-m')$interest_over_time %>%
                dplyr::select(date, !!.x := hits)) %>%
    reduce(full_join, by = 'date')


#         date cruise plane car
#1  2019-06-30     64    53  96
#2  2019-07-07     75    48  97
#3  2019-07-14     73    48 100
#4  2019-07-21     74    48 100
#5  2019-07-28     71    47 100
#6  2019-08-04     67    47  97
#7  2019-08-11     68    56  98
#.....
于 2020-06-27T12:57:43.770 回答