Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two data.frames in R with differing rows

Tags:

merge

r

I have two tables one with more rows than the other. I would like to filter the rows out that both tables share. I tried the solutions proposed here.

The problem, however, is that it is a large data-set and computation takes quite a while. Is there any simple solution? I know how to extract the shared rows of both tables using:

rownames(x1)->k
rownames(x)->l
which(rownames(x1)%in%l)->o

Here x1 and x are my data frames. But this only provides me with the shared rows. How can I get the unique rows of each table to then exclude them respectively? So that I can just cbind both tables together?

like image 503
Tim Heinert Avatar asked Apr 27 '26 23:04

Tim Heinert


1 Answers

(I edit the whole answer) You can merge both df with merge() (from Andrie's comment). Also check ?merge to know all the options you can put in as by parameter, 0 = row.names.

The code below shows an example with what could be your data frames (different number of rows and columns)

x = data.frame(a1 = c(1,1,1,1,1), a2 = c(0,1,1,0,0), a3 = c(1,0,2,0,0), row.names = c('y1','y2','y3','y4','y5'))
x1 = data.frame(a4 = c(1,1,1,1), a5 = c(0,1,0,0), row.names = c('y1','y3','y4','y5'))

Provided that row names can be used as identifier then we put them as a new column to merge by columns:

x$id <- row.names(x)
x1$id <- row.names(x1)

# merge by column names
merge(x, x1, by = intersect(names(x), names(x1)))

# result
#   id a1 a2 a3 a4 a5
# 1 y1  1  0  1  1  0
# 2 y3  1  1  2  1  1
# 3 y4  1  0  0  1  0
# 4 y5  1  0  0  1  0

I hope this solves the problem.

EDIT: Ok, now I feel silly. If ALL columns have different names in both data frames then you don't need to put the row name as another column. Just use:

merge(x,x1, by=0)
like image 69
julia Avatar answered Apr 30 '26 14:04

julia



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!