Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replicate by columns, but transposing in r with vectorization

I have a matrix like this:

m1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, byrow = TRUE)

and I would like to have every column repeated "m" times, but transposing into files and concat the results horizontally. I mean, suppose "m" is 3, I would like to have something like this:

matrix(c(1,4,7,2,5,8,3,6,9,1,4,7,2,5,8,3,6,9,1,4,7,2,5,8,3,6,9), 
                     nrow = 3, byrow = TRUE)

Is there any vectorized way to do this?

I have tried using rep to replicate the columns and then transposing, but I end with many rows

like image 828
Deyber Arley Valencia Avatar asked Mar 03 '26 01:03

Deyber Arley Valencia


1 Answers

We can use rep

matrix(rep(m1, each=nrow(m1)), nrow=3)

Or

`dim<-`(rep(m1, each=nrow(m1)), dim(m1)*c(1,3))

Or

t(replicate(nrow(m1), c(m1)))

data

m1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, byrow = TRUE)
like image 134
akrun Avatar answered Mar 05 '26 13:03

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!