Reputation: 67
I'm trying to combine two tables in R, so that the resulting table will get values from both table 1 and 2.
df1<-data.frame(Name = c("Gene_1", "Gene_2", "Gene_4", "Gene_3"), "1"=c(0,1,2,6), "2" = c(5,6,7,5), "3" = c(9,8,7,7), check.names=FALSE)
> df1
Name 1 2 3
1 Gene_1 0 5 9
2 Gene_2 1 6 8
3 Gene_4 2 7 7
4 Gene_3 6 5 7
df2<-data.frame(Name = c("Gene_2", "Gene_4", "Gene_5"), "1" = c(0,2,3), "2" = c(3,2,1), "3" = c(4,3,2), check.names=FALSE)
> df2
Name 1 2 3
1 Gene_2 0 3 4
2 Gene_4 2 2 3
3 Gene_5 3 1 2
the result should be something like:
1 Gene_1 0 5 9 NA NA NA
2 Gene_2 1 6 8 0 3 4
3 Gene_3 6 5 7 NA NA NA
4 Gene_4 2 7 7 2 2 2
5 Gene_5 NA NA NA 3 1 2
I feel that there must be some kind of easy way of doing it, rather than looping... It is not essential for output to sort the columns by any order, I just want to make sure that the right value goes in the right place. I've looked trough the forum, but still stuck( Thank you, Beth
Upvotes: 2
Views: 120
Reputation: 42689
merge
gets you there:
merge(df1, df2, by='Name', all=TRUE)
## Name 1.x 2.x 3.x 1.y 2.y 3.y
## 1 Gene_1 0 5 9 NA NA NA
## 2 Gene_2 1 6 8 0 3 4
## 3 Gene_3 6 5 7 NA NA NA
## 4 Gene_4 2 7 7 2 2 3
## 5 Gene_5 NA NA NA 3 1 2
Upvotes: 4