Given is the list below. This list contains character vectors of variable length.
l1 <- list("a" = c("x1", "x2", "x3"),
"b" = c("x4", "x5"),
"c" = c("x6", "x7", "x8", "x9"))
> l1
$a
[1] "x1" "x2" "x3"
$b
[1] "x4" "x5"
$c
[1] "x6" "x7" "x8" "x9"
The desired output, let's call it l2, is the following:
$a
[1] 1 1 1
$b
[1] 2 2
$c
[1] 3 3 3 3
This output has the following characteristics:
l2is a named list in which the names of the original listl1are preserved.- The length of list
l2is the same as listl1. - The order of list elements in
l1is preserved inl2. l2contains vectors with repeating integers. The length of each vector inl2is the same as the corresponding character vector inl1.
Part of solution
I found this post in which the statement below helped me to construct a partial solution.
The usual work-around is to pass it the names or indices of the vector instead of the vector itself.
l2 <- lapply(X = seq_along(l1),
FUN = function(x) rep(x, times = length(l1[[x]])))
l2
[[1]]
[1] 1 1 1
[[2]]
[1] 2 2
[[3]]
[1] 3 3 3 3
All criteria are met, except that the names are not preserved in l2.
How can I fix this in one go (not using a seperate statement after the lapply statement)?