I have a list of vectors and want to copy each vetor a certain amount of time. Thus, in the end I want to have list with copied vectors, for example 5 copies.
v1=c(1,2,3)
v2=c(4,5,6)
v3=c(7,8,9)
my_list=list(v1,v2,v3)
If I am applying rep it works, I got the copies, but I have to do it individually.
rep(my_list[1], times=5)
If am trying a for loop to do it automatically for each vector from the list, it does not work.
new_list = for (i in 1:3){
rep(my_list[i], times=5)
}
CodePudding user response:
You can subset your list with repeating indices:
my_list[rep(seq_along(my_list), each = 5)]
#> [[1]]
#> [1] 1 2 3
#>
#> [[2]]
#> [1] 1 2 3
#>
#> [[3]]
#> [1] 1 2 3
#>
#> [[4]]
#> [1] 1 2 3
#>
#> [[5]]
#> [1] 1 2 3
#>
#> [[6]]
#> [1] 4 5 6
#>
#> [[7]]
#> [1] 4 5 6
#>
#> [[8]]
#> [1] 4 5 6
#>
#> [[9]]
#> [1] 4 5 6
#>
#> [[10]]
#> [1] 4 5 6
#>
#> [[11]]
#> [1] 7 8 9
#>
#> [[12]]
#> [1] 7 8 9
#>
#> [[13]]
#> [1] 7 8 9
#>
#> [[14]]
#> [1] 7 8 9
#>
#> [[15]]
#> [1] 7 8 9
Created on 2021-10-07 by the reprex package (v2.0.0)
CodePudding user response:
Using replicate
do.call(c, replicate(5, my_list, simplify = FALSE))