list 我可以将一系列相似的数据帧合并到一个数据帧中吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5187794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:36:59  来源:igfitidea点击:

Can I combine a list of similar dataframes into a single dataframe?

listrdataframe

提问by David LeBauer

I have a dataframe:

我有一个数据框:

foo <- list(df1 = data.frame(x=c('a', 'b', 'c'),y = c(1,2,3)), 
            df2 = data.frame(x=c('d', 'e', 'f'),y = c(4,5,6)))

Can I convert it to a single dataframe of the form:

我可以将其转换为以下形式的单个数据帧:

data.frame(x = c('a', 'b', 'c', 'd', 'e', 'f'), y= c(1,2,3,4,5,6))

?

?

回答by Hong Ooi

do.call("rbind", foo)should do the trick.

do.call("rbind", foo)应该做的伎俩。

回答by Sacha Epskamp

with plyr:

plyr

foo <- list(df1 = data.frame(x=c('a', 'b', 'c'),y = c(1,2,3)), 
        df2 = data.frame(x=c('d', 'e', 'f'),y = c(4,5,6)))

library(plyr)
ldply(foo)[,-1]
  x y
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5
6 f 6

回答by Andrie

There are several problems with your code.

您的代码有几个问题。

The first is that the assignment statement in the list doesn't work. This needs to be fixed by, for example:

首先是列表中的赋值语句不起作用。这需要修复,例如:

foo <- list(
        df1 = data.frame(x=c('a', 'b', 'c'), y = c(1,2,3)), 
        df2 = data.frame(x=c('d', 'e', 'f'), y = c(4,5,6))
)

You can then use rbind() to combine the data frames:

然后您可以使用 rbind() 组合数据框:

rbind(foo$df1, foo$df2)

  x y
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5
6 f 6

But this poses more questions. For example, why do you combine the data frames in a list in the first place. The second is whether you really need to use data frames rather than vectors. Finally, I generally try to avoid rbind() and rather use merge() when combining data frames in this way.

但这带来了更多的问题。例如,为什么首先将列表中的数据框组合在一起。第二个是你是否真的需要使用数据框而不是向量。最后,在以这种方式组合数据帧时,我通常会尽量避免 rbind() 而是使用 merge() 。

回答by Chase

How about merge(foo[[1]], foo[[2]], all = TRUE)

怎么样 merge(foo[[1]], foo[[2]], all = TRUE)