rlistrep

Create list from names and unique vectors


I have this vector of non-syntactic names (integers), a list of unique vectors that I want to repeat each reps time to create a named list with names nms of length length(nms) where un_vecs are repeated each reps times. Any ideas how to do it?

#Input:
nms <- 1:5
un_vecs <- list(letters[1:3], letters[2:7])
reps <- c(2, 3)

#Expected output:
list(
  `1` = un_vecs[[1]],
  `2` = un_vecs[[1]],
  `3` = un_vecs[[2]],
  `4` = un_vecs[[2]],
  `5` = un_vecs[[2]]
)

# $`1`
# [1] "a" "b" "c"
# 
# $`2`
# [1] "a" "b" "c"
# 
# $`3`
# [1] "b" "c" "d" "e" "f" "g"
# 
# $`4`
# [1] "b" "c" "d" "e" "f" "g"
# 
# $`5`
# [1] "b" "c" "d" "e" "f" "g"

Solution

  • It was easier than I thought, since rep works on list:

    setNames(rep(un_vecs, times = reps), nms)