【问题标题】:using map function to create a dataframe from google trends data使用地图功能从谷歌趋势数据创建数据框
【发布时间】:2020-10-17 23:19:24
【问题描述】:

对于 r 来说相对较新,我有一个单词列表,我想通过 gtrendsr 函数查看 google 搜索命中,然后创建一个以日期作为索引并将每个单词的相关命中作为列的小标题,我我正在努力使用 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 循环的情况下如何做到这一点

【问题讨论】:

    标签: r tidyverse purrr gtrendsr


    【解决方案1】:

    假设每个关键字的 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 package (v0.3.0) 于 2020 年 6 月 27 日创建

    【讨论】:

      【解决方案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
      #.....
      

      【讨论】:

      • 谢谢!第一个给了我三个组合在一起的列表,但是单词名称没有得到执行,有没有办法做到这一点? map_df 方式虽然听起来更好,但它给了我错误 Error: Argument 1 must have names
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多