Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge data frames based on rownames in R

Tags:

merge

dataframe

r

How can I merge the columns of two data frames, containing a distinct set of columns but some rows with the same names? The fields for rows that don't occur in both data frames should be filled with zeros:

> d     a   b   c   d   e   f   g   h   i  j 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1 > e    k  l  m  n  o  p  q  r  s  t 1 11 12 13 14 15 16 17 18 19 20 3 21 22 23 24 25 26 27 28 29 30 > de     a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s  t 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19 20 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0  0 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29 30 
like image 937
barbaz Avatar asked Oct 12 '11 11:10

barbaz


People also ask

How do I merge two Dataframes by Rownames in R?

The merge() function in base R can be used to merge input dataframes by common columns or row names. The merge() function retains all the row names of the dataframes, behaving similarly to the inner join. The dataframes are combined in order of the appearance in the input function call.

How do I merge two data frames in R?

In R we use merge() function to merge two dataframes in R. This function is present inside join() function of dplyr package. The most important condition for joining two dataframes is that the column type should be the same on which the merging happens. merge() function works similarly like join in DBMS.

Does Cbind match Rownames?

Cbind: Combine objects by columns matching the rows on row names in mbojan/mbtools: Chaotic Collection of Functions and Datasets Possibly Useful Also To Others.

How do I merge two data frames in the same column in R?

To combine two data frames with same columns in R language, call rbind() function, and pass the two data frames, as arguments. rbind() function returns the resulting data frame created from concatenating the given two data frames. For rbind() function to combine the given data frames, the column names must match.


1 Answers

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names") R> de[is.na(de)] <- 0                 # replace NA values R> de   Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s 1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19 2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0 3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29    t 1 20 2  0 3 30 
like image 135
rcs Avatar answered Oct 15 '22 12:10

rcs