[R] merging dataframes

Dimitris Rizopoulos dimitris.rizopoulos at med.kuleuven.be
Thu Nov 3 14:33:36 CET 2005


you could use something like:

mat1$id1 <- 1:nrow(mat1)
mat2$id2 <- 1:nrow(mat2)

out <- merge(mat1, mat2, all = TRUE)
out[order(out$id1, out$id2), ]

I hope it helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://www.med.kuleuven.be/biostat/
     http://www.student.kuleuven.be/~m0390867/dimitris.htm


----- Original Message ----- 
From: "Gavin Simpson" <gavin.simpson at ucl.ac.uk>
To: "R-help" <R-help at stat.math.ethz.ch>
Sent: Thursday, November 03, 2005 2:08 PM
Subject: [R] merging dataframes


> 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
> 


Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm




More information about the R-help mailing list