Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to union tables in R?

Tags:

r

I am trying to union two tables. Every month I get new data coming in. It will be handy for me to add the new data to the existing dataframe. I am not seeking to merge them as they are the same variables.

A little example as follow: M and N have the same dimension. I would like to combine M and N together

Thanks in advance

M <- structure(list(ID= c(56L, 67L, 68L, 73L, 77L, 87L), Mary = c(73L, 
82L, 80L, 78L, 79L, 80L), Dave = c(45L, 42L, 51L, 46L, 60L, 54L
), Anne = c(78L, 85L, 92L, 83L, 77L, 89L), Bob = c(51L, 49L, 
58L, 54L, 62L, 68L)), .Names = c("ID", "Mary", "Dave", "Anne", 
"Bob"), class = "data.frame", row.names = c(NA, -6L))

N <- structure(list(ID= c(53L, 22L, 21L, 73L, 727L, 27L), Mary = c(72L, 
82L, 80L, 78L, 79L, 80L), Dave = c(45L, 42L, 51L, 46L, 62L, 54L
), Anne = c(78L, 85L, 92L, 22L, 77L, 89L), Bob = c(52L, 49L, 
58L, 54L, 62L, 628L)), .Names = c("ID", "Mary", "Dave", "Anne", 
"Bob"), class = "data.frame", row.names = c(NA, -6L))
like image 476
Luo Lei Avatar asked Oct 30 '25 08:10

Luo Lei


1 Answers

This might be all you need:

MN <- rbind(M, N)

If the two data.frames have different columns, then I would recommend this instead:

library(plyr)
MN <- rbind.fill(M, N)

Finally, if you need to remove duplicates:

MN <- MN[!duplicated(MN),]
like image 107
flodel Avatar answered Nov 01 '25 22:11

flodel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!