[英]Merge multiple data.frames in R with varying row length
I'm relatively new to R and trying to figure out how to merge multiple data.frames with varying numbers of rows but all with a common column, "Year". 我对R比较陌生,试图弄清楚如何将多个data.frames与不同数量的行合并,但所有行都有一个共同的列“Year”。 I've looked through similar questions, and this question: Merge dataframes, different lengths provided a great answer. 我看过类似的问题,这个问题: 合并数据帧,不同的长度提供了一个很好的答案。 However, when I applied it to my own data, I couldn't get it to work with multiple data.frames; 但是,当我将它应用于我自己的数据时,我无法使用多个data.frames; I always receive an error message. 我总是收到一条错误消息。
Sample data: 样本数据:
> df1 <- data.frame(Year=2006:2011, Site1=c("2.3", "1" , "3.1", "2.9", "1.4", "3"))
> df2 <- data.frame(Year=2007:2011, Site2=c("2.7", "4.1", "1.1", "2.6", "3.1"))
> df3 <- data.frame(Year=2008:2011, Site3=c("1.3", "2" , "3.6", "1.7"))
The goal is to produce a single data.frame where column 1 is the year, column 2 is site 1, column 3 is site 2, and so on. 目标是生成单个data.frame,其中第1列是年份,第2列是站点1,第3列是站点2,依此类推。 I have ~17 data.frames currently (there will be up to 40), corresponding to 17 sites with variable timelines/number of rows. 我目前有~17个data.frames(最多40个),对应17个具有可变时间轴/行数的站点。
Any help would be appreciated. 任何帮助,将不胜感激。
Code I've tried: 代码我尝试过:
> NewDF <- merge(df1, df2, by="Year", all.x=TRUE, all.y=TRUE)
This worked great for 2 data.frames, but when I tried to add in another data.frame, I received the error message: 这适用于2个data.frames,但当我尝试添加另一个data.frame时,我收到了错误消息:
> NewDF <- merge(list=c(df1, df2, df3), by="Year", all.x=TRUE, all.y=TRUE)
Error in as.data.frame(x) : argument "x" is missing, with no default
You want to merge the result with df3
, ie: 您想要将结果与df3
合并,即:
merge(df3, merge(df1, df2, by="Year", all.x=TRUE, all.y=TRUE), by = "Year", all.x = TRUE, all.y = TRUE)
# Year Site3 Site1 Site2
#1 2006 <NA> 2.3 <NA>
#2 2007 <NA> 1 2.7
#3 2008 1.3 3.1 4.1
#4 2009 2 2.9 1.1
#5 2010 3.6 1.4 2.6
#6 2011 1.7 3 3.1
Or if you have your data.frame
's in a list, use Reduce
to generalize the above: 或者,如果您将data.frame
放在列表中,请使用Reduce
来概括上述内容:
Reduce(function(x,y) merge(x, y, by = "Year", all.x = TRUE, all.y = TRUE),
list(df1, df2, df3))
# Year Site1 Site2 Site3
#1 2006 2.3 <NA> <NA>
#2 2007 1 2.7 <NA>
#3 2008 3.1 4.1 1.3
#4 2009 2.9 1.1 2
#5 2010 1.4 2.6 3.6
#6 2011 3 3.1 1.7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.