user5054
user5054

Reputation: 1096

How to concatenate column repetitions of a matrix without a for loop

Let's say I have the below matrix:

     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6

I want to generate a matrix which is the concatenation (by column) of matrices that are generated by repetition of each column k times. For example, when k=3, below is what 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 that without a for loop?

Upvotes: 3

Views: 82

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

We can repeat each element of matrix k times and fit the vector in a matrix where number of columns is k times the original one.

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

Upvotes: 2

josliber
josliber

Reputation: 44330

You can do this with column indexing. A convenient way to repeat each column number the correct number of times is the rep function:

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

In the above expression, seq_len(ncol(mat)) is the sequence from 1 through the number of columns in the matrix (you could think of it like 1:ncol(mat), except it deals nicely with some special cases like 0-column matrices).

Data:

(mat <- matrix(1:6, nrow=3, byrow = TRUE))
#      [,1] [,2]
# [1,]    1    2
# [2,]    3    4
# [3,]    5    6

Upvotes: 5

Related Questions