name character vectors with same name of list

  • A+
Category:Languages

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" 

 


We unlist the list while setting the names by replicating

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)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: