I have a list that looks like this.
my_list <- list(Y = c("p", "q"), K = c("s", "t", "u"))
I want to name each list element (the character vectors) with the name of the list they are in. All element of the same vector must have the same name
I was able to write this function that works on a single list element
name_vector <- function(x){
names(x[[1]]) <- rep(names(x[1]), length(x[[1]]))
return(x)
}
> name_vector(my_list[1])
$Y
Y Y
"p" "q"
But can't find a way to vectorize it. If I run it with an apply function it just returns the list unchanged
> lapply(my_list, name_vector)
$K
[1] "p" "q"
$J
[1] "x" "y"
My desired output for my_list is a named vector
Y Y K K K
"p" "q" "s" "t" "u"
if your names don't end with numbers :
vec <- unlist(my_list)
names(vec) <- sub("\\d+$","",names(vec))
vec
# Y Y K K K
# "p" "q" "s" "t" "u"
We unlist
the list
while setting the names by rep
licating
setNames(unlist(my_list), rep(names(my_list), lengths(my_list)))
Or stack
into a two column data.frame, extract the 'values' column and name it with 'ind'
with(stack(my_list), setNames(values, ind))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With