[R] merging dataframes
Gavin Simpson
gavin.simpson at ucl.ac.uk
Thu Nov 3 14:08:18 CET 2005
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.
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
More information about the R-help
mailing list