Home > Software engineering >  How to interlacely merge two matrices in R?
How to interlacely merge two matrices in R?

Time:09-27

I am facing with the other problem in coding with R-Studio. I have two dataframes (with the same number of rows and colunms). Now I want to merge them two into one, but the 6 columns of dataframe 1 would be columns 1,3,5,7,9.11 in the new matrix; while those of data frame 2 would be 2,4,6,8,10,12 in the new merged dataframe.

I can do it with for loop but is there any smarter way/function to do it? Thank you in advance ; )

CodePudding user response:

You can cbind them and then reorder the columns accordingly:

df1 <- as.data.frame(sapply(LETTERS[1:6], function(x) 1:3))
df2 <- as.data.frame(sapply(letters[1:6], function(x) 1:3))

cbind(df1, df2)[, matrix(seq_len(2*ncol(df1)), 2, byrow=T)]
#   A a B b C c D d E e F f
# 1 1 1 1 1 1 1 1 1 1 1 1 1
# 2 2 2 2 2 2 2 2 2 2 2 2 2
# 3 3 3 3 3 3 3 3 3 3 3 3 3

CodePudding user response:

The code below will produce your required result, and will also work if one data frame has more columns than the other

# create sample data
df1 <- data.frame(
    a1 = 1:10,
    a2 = 2:11,
    a3 = 3:12,
    a4 = 4:13,
    a5 = 5:14,
    a6 = 6:15
)

df2 <- data.frame(
    b1=11:20,
    b2=12:21,
    b3=13:22,
    b4=14:23,
    b5=15:24,
    b6=16:25
)

# join by interleaving columns
want <- cbind(df1,df2)[,order(c(1:length(df1),1:length(df2)))]

Explanation:

  • cbind(df1,df2) combines the data frames with all the df1 columns first, then all the df2 columns.
  • The [,...] element re-orders these columns.
  • c(1:length(df1),1:length(df2)) gives 1 2 3 4 5 6 1 2 3 4 5 6 - i.e. the order of the columns in df1, followed by the order in df2
  • order() of this gives 1 7 2 8 3 9 4 10 5 11 6 12 which is the required column order
  • So [, order(c(1:length(df1), 1:length(df2)] re-orders the columns so that the columns of the original data frames are interleaved as required.
  • Related