简体   繁体   中英

R merge dataframes in specific order

I have three equal-sized data frames that I want to merge in a particular order so that I can then use write.table to make a formatted text file for use in another program.

I want this:

dataframeA_col1 dataframeB_col1 dataframeC_col1 dataframeA_col2 dataframeB_col2 dataframeC_col2 etc...

Not this: dataframeA_col1 dataframeA_col2 dataframeB_col1 dataframeB_col2

I started to write the loop below which works but only gives me the first 3 columns. How can I fix this loop, or is there a better approach?

temp <- c()
for(i in length(dataframeA)){
temp <- cbind(temp, dataframeA[,i], dataframeB[,i], dataframeC[,i])
i <- i+1
}

Sure, here's a loop-less way:

dfA <- data.frame(col1 = 1:4, col2 = 1:4, col3 = 1:4)
dfB <- dfA
dfC <- dfA
colSeq <- c ( matrix(1 : (3*ncol(dfA)), 3, ncol(dfA), byrow = TRUE) )

where colSeq is your desired column sequence:

> colSeq
[1] 1 4 7 2 5 8 3 6 9 

and now use this colSeq to rearrange the columns of cbind(dfA,dfB,dfC) :

> cbind(A = dfA, B = dfB, C = dfC)[, colSeq ]
  A.col1 B.col1 C.col1 A.col2 B.col2 C.col2 A.col3 B.col3 C.col3
1      1      1      1      1      1      1      1      1      1
2      2      2      2      2      2      2      2      2      2
3      3      3      3      3      3      3      3      3      3
4      4      4      4      4      4      4      4      4      4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM