6

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"
markus
  • 25,843
  • 5
  • 39
  • 58

2 Answers2

8

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))
akrun
  • 874,273
  • 37
  • 540
  • 662
4

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" 
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167