从R中的3个data.frames创建一个data.frame

时间:2013-12-15 12:57:35

标签: r dataframe

我在R中遇到问题,我无法弄清楚如何解决。我有3个数据框,例如:

data1 = 
Stuff Freq
X     12 
Y     3
Z     4

data2 = 
Stuff Freq
X     6 
Y     5
W     8

data3 = 
Stuff Freq
Z     7
Y     4

我想从这些中创建一个data.frame,如下所示:

data = 
Stuff  Freq1  Freq2  Freq3    
X         12      6      0
Y          3      5      7
Z          4      0      4
W          0      8      0

我试过了:

data <- as.data.frame(c(data1[,1], data2[,1], data3[,1]), cbind(data1[,2], data2[,2], data3[,2])); 

但它不起作用。有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:2)

您正在寻找merge

data1 <- data.frame(Stuff=c("X","Y","Z"), Freq=c(12,3,4)) 
data2 <- data.frame(Stuff=c("X","Y","W"), Freq=c(6,5,8)) 
data3 <- data.frame(Stuff=c("Z","Y"), Freq=c(7,4)) 

res <- merge(merge(data1, data2, by="Stuff", all=TRUE), 
             data3, by="Stuff", all=TRUE)
names(res)[-1] <- paste0("Freq", 1:3)

res[is.na(res)] <- 0

#   Stuff Freq1 Freq2 Freq3
# 1     X    12     6     0
# 2     Y     3     5     4
# 3     Z     4     0     7
# 4     W     0     8     0

答案 1 :(得分:1)

与Roland相同的想法,但是对于任意数量的data.frames都是一个线性解决方案和通用:

  Reduce(function(x,y){
            res <- merge(x,y,by=1,all=T)
            res[is.na(res)] <- 0
            res
        },
     mget(ls(pattern='data.*')))
  Stuff Freq.x Freq.y Freq
1     X     12      6    0
2     Y      3      5    4
3     Z      4      0    7
4     W      0      8    0