对于 r 中的循环:如何将每次迭代的多个输出存储在一行而不是单独的行中?

For loop in r: how to store multiple outputs of each iteration in one row instead of in separate rows?

我试图通过运行以下代码将每一轮迭代的多个输出存储在r中的for循环中,但每次迭代的多个输出分别存储在不同的行中。我使用的代码以及通过这段代码得到的结果如下:

我使用的代码:

result_issue <- data.frame()
for (i in 1:3){
  web <- read_html(link[i])
  news_issue <- web %>% html_nodes('li.m-list__item a')
  issue1 <- news_issue %>% html_text()
  this_result_issue <- data.frame(issue1)
  result_issue <- rbind(result_issue, this_result_issue)
}
result_issue

我实际得到的结果: 前三行是第一次迭代的输出,第4、5行是第二次迭代的输出,最后三行是第三次迭代的输出。

issue1
1 Facebook Fact-checks
2          Coronavirus
3         TikTok posts
4 Facebook Fact-checks
5       Facebook posts
6 Facebook Fact-checks
7          Coronavirus
8             Bloggers

我期望的结果是这样的:每次迭代的输出保存在一行中

issue1
1 Facebook Fact-checks; Coronavirus; TikTok posts
2 Facebook Fact-checks; Facebook posts
3 Facebook Fact-check; Coronavirus; Bloggers

有什么想法请赐教。非常感谢您的帮助!

我建议您使用这部分代码:

  web <- read_html(link[i])
  news_issue <- web %>% html_nodes('li.m-list__item a')
  issue1 <- news_issue %>% html_text()

并放入sapplysapply 的好处是输出向量是 pre-allocated,这样您就不会创建一个不断增长的对象。参见 circle 2 of the R inferno

在每一步中,要将 issue 作为由 '; ' 分隔的单个字符串,您可以将 pastecollapse 结合使用。

获得输出向量后,您可以使用它来创建数据框。

set.seed(10)

result_issue_vec <- 
  sapply(1:3, function(i) {
    # web <- read_html(link[i])
    # news_issue <- web %>% html_nodes('li.m-list__item a')
    # issue1 <- news_issue %>% html_text()
    issue1 <- sample(letters, sample(1:4, 1))
    paste(issue1, collapse = '; ')
  })

data.frame(issue1 = result_issue_vec)
#>       issue1
#> 1    i; j; p
#> 2 w; h; v; g
#> 3    s; x; o

reprex package (v2.0.1)

于 2022-02-18 创建