How to concatenate repetitions of matrix columns without a for loop
Let's say I have the following matrix:
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
I want to generate a matrix that is a concatenation (column wise) of matrices that are generated by repeating each column k
times. For example, when k=3
, below I want to get:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 1 2 2 2
[2,] 3 3 3 4 4 4
[3,] 5 5 5 6 6 6
How can I do this without a for loop ?
source to share
You can do this using column indexing. A convenient way to repeat each column number the correct number of times is with a function rep
:
mat[,rep(seq_len(ncol(mat)), each=3)]
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 1 1 2 2 2
# [2,] 3 3 3 4 4 4
# [3,] 5 5 5 6 6 6
The above expression seq_len(ncol(mat))
is a sequence of 1 based on the number of columns in the matrix (you can think of it like 1:ncol(mat)
that, except that it goes well with some special cases like matrices with 0 columns).
Data:
(mat <- matrix(1:6, nrow=3, byrow = TRUE))
# [,1] [,2]
# [1,] 1 2
# [2,] 3 4
# [3,] 5 6
source to share
We can repeat each element of the matrix k
times and match the vector in the matrix, where the number of columns is k
times original.
k <- 3
matrix(rep(t(mat), each = k), ncol = ncol(mat) * k, byrow = TRUE)
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 1 1 2 2 2
#[2,] 3 3 3 4 4 4
#[3,] 5 5 5 6 6 6
source to share