Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R-Duplicate columns in a matrix

Tags:

r

I have a matrix

1   2
1   3

I want to duplicate each columns three times to create a matrix like this:

1   1   1   2   2   2
1   1   1   3   3   3

I dont think I can use rep. Really appreciate any help

like image 629
Tuan Do Avatar asked Sep 20 '25 08:09

Tuan Do


2 Answers

You can use rep in this situation, just not on the matrix itself. This does what you want:

mat1 = cbind(c(1,1), c(2,3))
mat2 = mat1[, rep(1:2, each=3)]
like image 169
dfg3533 Avatar answered Sep 21 '25 22:09

dfg3533


You can actually do it with a single rep inside matrix.

m <- matrix(c(1, 1, 2, 2), nrow = 2)
matrix(rep(as.numeric(t(m)), each = 3), nrow = nrow(m), byrow = TRUE)

Depending on the size of your matrix this might be quicker than using apply.

like image 26
Romero Morais Avatar answered Sep 21 '25 21:09

Romero Morais