Search code examples
rapplyrep

Repeat vector elements according to values in matrix


I want to repeat each element in a vector 'A', the number of times specified in a matrix 'a'. The columns in the matrix correspond to each element in the vector. The number of repetitions to be applied are obtained from the matrix row-wise.

A <- c("China", "Alabama")
a <- matrix(c(1,2,1,0),2,2)
a
#      [,1] [,2]
# [1,]    1    1
# [2,]    2    0

In the example, the first row of 'a' ([1,] 1 1) specifies that "China" should be repeated 1 time, and "Alabama" 1, and so on.

The result should be a list with one element per row of the matrix:

output <- list(c("China", "Alabama"), c("China", "China"))
output
# [[1]]
# [1] "China"   "Alabama" 
#
# [[2]]
# [1] "China" "China"

This can be easily done by double loop, but in my actual case a is 170 000 x 250 matrix and A is 1x250 vector and i am trying to make code as faster as possible taking into account that apply is faster than loop.

I tried to run following apply command:

apply(a, 1, function(x,y) rep(y,x), x=a, y=A)

But it does not work since a is not a row of a but the whole matrix and i have no idea how to introduce row of a in apply. Also I am not able to download packages. Can you help me please.


Solution

  • You can use lapply with asplit and rep.

    lapply(asplit(a,1), rep, x=A)
    #[[1]]
    #[1] "China"   "Alabama"
    #
    #[[2]]
    #[1] "China" "China"