Stack Overflow Asked by Maksim Tarasenko on November 22, 2021
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 1×250 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.
Another base R option
> lapply(data.frame(t(a)),rep, x = A)
$X1
[1] "China" "Alabama"
$X2
[1] "China" "China"
Answered by ThomasIsCoding on November 22, 2021
You can use lapply
with asplit
and rep
.
lapply(asplit(a,1), rep, x=A)
#[[1]]
#[1] "China" "Alabama"
#
#[[2]]
#[1] "China" "China"
Answered by GKi on November 22, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP