如何使用Purrr/reduce组合数据框对象

huangapple go评论51阅读模式
英文:

how to use Purrr/reduce combine dataframe objects

问题

在R环境中有名为'data_1\data_2\....data_20'的data.frame对象,
reduce(objects, rbind)失败了,有人可以帮忙吗?谢谢!

library(tidyverse)
for (i in c(1:20)){
  assign(paste0('data_', i), data.frame(category = c('a', 'b'), sales = c(1, 2)))
}

objects <- ls(pattern = 'data') %>% as.list() 
data_total <- reduce(objects, rbind)

下面的代码可以工作,但必须将data_1\data_2\....data_20作为参数输入:

data_total <- reduce(list(data_1, data_2), rbind)
英文:

There are data.frame objects in R environment named as &#39;data_1\data_2\....data_20&#39;,
reduce(objects,rbind) failed ,anyone can help ? Thanks!

library(tidyverse)
for (i in c(1:20)){
  assign(paste0(&#39;data_&#39;,i),data.frame(category=c(&#39;a&#39;,&#39;b&#39;),sales=c(1,2)))
}

objects &lt;- ls(pattern=&#39;data&#39;) %&gt;%  as.list() 
data_total &lt;- reduce(objects,rbind)

below code can work,but have to input data_1\data_2\....data_20 as parmeter

data_total &lt;- reduce(list(data_1,data_2),rbind)

答案1

得分: 1

以下是翻译好的部分:

你可以这样做:

library(tidyverse)

data_frames <- str_c("data_", 1:20)

map_dfr(data_frames, get)

请注意,代码部分没有进行翻译。

英文:

You can do this:

library(tidyverse)

data_frames &lt;- str_c(&quot;data_&quot;, 1:20)

map_dfr(data_frames, get)

huangapple
  • 本文由 发表于 2023年4月4日 16:19:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定