lorenzbr
lorenzbr

Reputation: 191

R Split matrix and merge them

I am looking for a more elegant R code that does the following:

mat <- matrix(data = c(1,1,0,0,1,1,2,2,2,0,0,0,0,1,1,2,2,2), nrow = 3)
colnames(mat) <- c("x1","x2","x3","x1","x2","x3")
len <- 2
ncol.mat <- 1:NCOL(mat)

split.vec <- split(ncol.mat, cut(ncol.mat, breaks = len))
split.vec <- as.data.frame(split.vec)

new.mat <- data.frame()

for(i in 1:len){
  vv <- mat[,split.vec[,i]]
  new.mat <- rbind(new.mat,vv)
}

new.mat

Does anyone have a nice way to do this? I haven't found an elegant solution, but I'm sure there is a very simple solution to this. Thanks for helping.

Upvotes: 1

Views: 93

Answers (1)

akrun
akrun

Reputation: 887501

Try:

  apply(array(mat, dim=c(3,3,2)),2, c)
  #     [,1] [,2] [,3]
  #[1,]    1    0    2
  #[2,]    1    1    2
  #[3,]    0    1    2
  #[4,]    0    0    2
  #[5,]    0    1    2
  #[6,]    0    1    2

Or

  m2 <- aperm(array(mat, dim=c(3,3,2)), c(1,3,2))
  dim(m2) <- c(prod(dim(m2)[-1]), dim(m2)[1])
   m2
  #      [,1] [,2] [,3]
  # [1,]    1    0    2
  # [2,]    1    1    2
  # [3,]    0    1    2
  # [4,]    0    0    2
  # [5,]    0    1    2
  # [6,]    0    1    2

Upvotes: 1

Related Questions