2

I have two sets of data:

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"   

I want to combine these into one data frame so that it will look like this:

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"   

I thought c <- rbind(a$town, b$town) would work but didn't have any success.

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Danny
  • 554
  • 1
  • 6
  • 17

2 Answers2

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
TomNash
  • 3,147
  • 2
  • 21
  • 57
1

Here is a base R approach...

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

If you wanna go the package route I'd recommend plyr::rbind.fill

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

Notice that I had to transform a and b into data.frames because in your example they are actually matrices.

Jacob H
  • 4,317
  • 2
  • 32
  • 39
  • Thanks for the resolution but the data from the point 3 columns are now distributed in two columns. I actually have multiple columns that need to align in my actual data set so am hoping there is a solution where I would not need to merge them manually. town point1 point2 point3.x point3.y 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 4 7 f 5 > – Danny Feb 01 '16 at 19:43
  • If you don't want to specify column names manually, you can use their intersect, as in `merge(a, b, by = intersect(colnames(a), colnames(b)), all = TRUE)` – David Arenburg Feb 01 '16 at 19:46
  • @Danny I changed it. Both responds yield the desired result. David's comment will work in the general case. – Jacob H Feb 01 '16 at 19:47