使用来自单独数据框的数据向数据框添加新行

时间:2016-02-01 19:32:21

标签: r rows

我有两组数据:

town <- c("a","b","c","d","e")
point1 <- c(1,2,3,4,5)
point2 <- c(3,6,1,7,9)
point3 <- c(1,76,3,77,32)
a <- cbind(town,point1,point2,point3)

     town point1 point2 point3
[1,] "a"  "1"    "3"    "1"   
[2,] "b"  "2"    "6"    "76"  
[3,] "c"  "3"    "1"    "3"   
[4,] "d"  "4"    "7"    "77"  
[5,] "e"  "5"    "9"    "32"  

town <- c("f","f")
point3 <- c(4,5)
b <- cbind(town,point3)

     town point3
[1,] "f"   "4"   
[2,] "f"   "5"   

我想将它们组合成一个数据框,使它看起来像这样:

town<-c("a","b","c","d","e","f","f")
point1<-c(1,2,3,4,5,NA,NA)
point2<-c(3,6,1,7,9,NA,NA)
point3<-c(1,76,3,77,32,4,5)
c<-cbind(town,point1,point2,point3)

     town point1 point2 point3
[1,] "a"  "1"    "3"    "1"   
[2,] "b"  "2"    "6"    "76"  
[3,] "c"  "3"    "1"    "3"   
[4,] "d"  "4"    "7"    "77"  
[5,] "e"  "5"    "9"    "32"  
[6,] "f"  NA     NA     "4"   
[7,] "f"  NA     NA     "5"   

我认为c <- rbind(a$town, b$town)可行,但没有取得任何成功。

2 个答案:

答案 0 :(得分:2)

library(gtools)
smartbind(a,b)
    town point1 point2 point3
1:1    a      1      3      1
1:2    b      2      6     76
1:3    c      3      1      3
1:4    d      4      7     77
1:5    e      5      9     32
2:1    f   <NA>   <NA>      4
2:2    f   <NA>   <NA>      5

答案 1 :(得分:1)

这是基础R方法......

res <- merge(a, b, by= c("town", "point3"), all = TRUE)

如果你想走包裹路线,我建议你plyr::rbind.fill

res <- rbind.fill(as.data.frame(a),as.data.frame(b))

请注意,我必须将ab转换为data.frame,因为在您的示例中,它们实际上是矩阵。