[R] Merge and specify column output order

arun smartpink111 at yahoo.com
Wed Jan 15 23:15:43 CET 2014


Hi,

It would be better to post a reproducible example.

set.seed(42)
 df1 <- cbind(as.data.frame(matrix(sample(60,40,replace=TRUE),ncol=4)),date=seq(as.Date("2013-05-10"),length.out=10,by=1))
colnames(df1)[-5] <- paste0("mod",1:4)

 set.seed(14)
 df2 <- data.frame(obs=1:20,wy=sample(12,20,replace=TRUE),date=seq(as.Date("2013-05-12"),length.out=20,by=3))
 An <- c(colnames(df1),colnames(df2))
merge(df1,df2,by=c("date"))[,An[!duplicated(An,fromLast=TRUE)]]
#  mod1 mod2 mod3 mod4 obs wy       date
#1   18   57   60   24   1  4 2013-05-12
#2   32   57   31   50   2  8 2013-05-15
#3   40   29   27   55   3 12 2013-05-18


A.K.


On Wednesday, January 15, 2014 4:44 PM, Janet Choate <jsc.eco at gmail.com> wrote:
Hi,

i am merging two data frames of different time periods, so that the result
contains data from both for the same time period.
however, I want the result to output columns in a certain order.
the common column between the two data frames is date.

for example:

df1 columns:
mod1 mod2 mod3 mod4 date  #(there are actually 691 mod columns)

df2 columns:
obs wy date

after merge, i want the order of the columns to be all mod data columns
from df1, followed by the obs and wy columns from df2, followed by the date
column.

i almost get want i want with (at least it doesn't put the common column
date as the first column as merge does by default):

new = merge(df1, df2, by=c("date"))[, union(names(df1), names(df2))]

however, that of course gives me all of df1 followed by all of df2, which
doesn't put obs immediately after the mod columns:

what i get:
mod1 mod2 mod3 mod4 date obs wy

what i want:
mod1 mod2 mod3 mod4 obs wy date

any suggestions on how to output the columns in the order i want, without
having to rearrange the order after the fact?

thank you for any help!
Janet

    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.





More information about the R-help mailing list