【问题标题】:Append the results of a function call on a vector to one another in r将向量上的函数调用的结果彼此附加到 r 中
【发布时间】:2019-06-30 03:12:54
【问题描述】:

我有一个 1 列数据框,其唯一列中有一系列 URL(可能是一个相同的向量)。为了这个示例,我们将保持每个 URL 相同:

urls<-as.data.frame(c("https://en.wikipedia.org/wiki/List_of_counties_in_California", "https://en.wikipedia.org/wiki/List_of_counties_in_California","https://en.wikipedia.org/wiki/List_of_counties_in_California"))
colnames(urls)<-"col1"
urls$col1<-as.character(urls$col1)

我还编写了一个从这些 url 中抓取表格的函数:

wiki_scrape <- function(x){
  x_url <- x %>%
    read_html() %>%
    html_nodes(xpath='//*[@id="mw-content-text"]/div/table[2]') %>%
    html_table() %>%
    .[[1]] %>%
    select(County)
  return(x_url) 
}

wiki_scrape(urls[1,1]) 的结果是一个包含 58 个观察值的数据框。我想在整个向量urls(而不仅仅是urls[1,1])上以迭代方式运行这个函数wiki_scrape,并将每个结果数据帧附加到前一个结果数据帧。在此示例中,urls 列出了 3 个 url,因此我希望生成的数据帧长度为 174 个观察值(3*58 = 174,其中 58 是使用wiki_scrape 抓取的一个数据帧的长度)。

【问题讨论】:

  • 你不是说 do.call(rbind ..,是吗?(do.call(rbind, lapply(urls, wiki_scrape)))

标签: r function append


【解决方案1】:

你可以的

library(dplyr)

map(urls$col1, wiki_scrape) %>% bind_rows() 

#            County
#1   Alameda County
#2    Alpine County
#3    Amador County
#4     Butte County
#5 Calaveras County
#6    Colusa County
#....

【讨论】:

    【解决方案2】:

    我们可以从purrr使用map_df

    library(purrr)
    out <- map_df(urls$col1, wiki_scrape)
    head(out)
    #            County
    #1   Alameda County
    #2    Alpine County
    #3    Amador County
    #4     Butte County
    #5 Calaveras County
    #6    Colusa County
    

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 2011-12-28
      • 2019-11-19
      • 1970-01-01
      相关资源
      最近更新 更多