[R] merging dataframes

Liaw, Andy andy_liaw at merck.com
Thu Nov 3 14:33:46 CET 2005


The `Value' section of ?merge does say that `... in all cases the result has
no special row names', so you're left to handle that on your own.  One
possibility is to use

  result <- merge(mat1, mat2, all=TRUE, sort=FALSE)

so that the sorting is not done, then you can just do

  rownames(result) <- c(rownames(mat1), rownames(mat2))

Cheers,
Andy


> From: Gavin Simpson
> 
> Dear List,
> 
> I often have to merge two or more data frames containing unique row
> names but with some columns (names) common to the two data frames and
> some columns not common. This toy example will explain the 
> kind of setup
> I am talking about:
> 
> mat1 <- as.data.frame(matrix(rnorm(20), nrow = 5))
> mat2 <- as.data.frame(matrix(rnorm(20), nrow = 4))
> rownames(mat1) <- paste("site", 1:5, sep="")
> rownames(mat2) <- paste("site", 6:9, sep="")
> names(mat1) <- paste("species", c(1,3,5,7), sep="")
> names(mat2) <- paste("species", c(2,3,4,7,9), sep="")
> mat1
> mat2
> 
> So sites (rows) are unique across both data frames, but there 
> are only 7
> unique species (columns):
> 
> unique(c(names(mat1), names(mat2)))
> 
> merge(mat1, mat2, all = TRUE)
> 
> gives almost what I want, but it drops or looses the rownames()
> information from the two merged data frames, and it re-orders the rows
> so that one simply cannot write back the correct row names.
> 
> How might I go about merging two data frames as I have described, but
> preserve the row names and more importantly, keep the order 
> of rows the
> same, so that rows from mat1 come before the rows of mat2?
> 
> Many thanks,
> 
> Gavin
> -- 
> %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~
> %~%~%~%~%
> Gavin Simpson                     [T] +44 (0)20 7679 5522
> ENSIS Research Fellow             [F] +44 (0)20 7679 7565
> ENSIS Ltd. & ECRC                 [E] gavin.simpsonATNOSPAMucl.ac.uk
> UCL Department of Geography       [W] 
> http://www.ucl.ac.uk/~ucfagls/cv/
> 26 Bedford Way              
>       [W] http://www.ucl.ac.uk/~ucfagls/
> London.  WC1H 0AP.
> %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~
> %~%~%~%~%
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list