我从 4 个 df 收集数据,并希望按行名合并它们。我正在寻找一种有效的方法来做到这一点。这是我拥有的数据的简化版本。
df1 <- data.frame(N= sample(seq(9, 27, 0.5), 40, replace= T),
P= sample(seq(0.3, 4, 0.1), 40, replace= T),
C= sample(seq(400, 500, 1), 40, replace= T))
df2 <- data.frame(origin= sample(c("A", "B", "C", "D", "E"), 40,
replace= T),
foo1= sample(c(T, F), 40, replace= T),
X= sample(seq(145600, 148300, 100), 40, replace= T),
Y= sample(seq(349800, 398600, 100), 40, replace= T))
df3 <- matrix(sample(seq(0, 1, 0.01), 40), 40, 100)
df4 <- matrix(sample(seq(0, 1, 0.01), 40), 40, 100)
rownames(df1) <- paste("P", sprintf("%02d", c(1:40)), sep= "")
rownames(df2) <- rownames(df1)
rownames(df3) <- rownames(df1)
rownames(df4) <- rownames(df1)
这是我通常会做的:
# merge df1 and df2
dat <- merge(df1, df2, by= "row.names", all.x= F, all.y= F) #merge
rownames(dat) <- dat$Row.names #reset rownames
dat$Row.names <- NULL #remove added rownames col
# merge dat and df3
dat <- merge(dat, df3, by= "row.names", all.x= F, all.y= F) #merge
rownames(dat) <- dat$Row.names #reset rownames
dat$Row.names <- NULL #remove added rownames col
# merge dat and df4
dat <- merge(dat, df4, by= "row.names", all.x= F, all.y= F) #merge
rownames(dat) <- dat$Row.names #reset rownames
dat$Row.names <- NULL #remove added rownames col
如您所见,这需要大量代码。我的问题是,是否可以通过更简单的方法实现相同的结果。我试过(没有成功):更新:现在可以了!
MyMerge <- function(x, y){
df <- merge(x, y, by= "row.names", all.x= F, all.y= F)
rownames(df) <- df$Row.names
df$Row.names <- NULL
return(df)
}
dat <- Reduce(MyMerge, list(df1, df2, df3, df4))
在此先感谢您的任何建议