name character vectors with same name of list
Asked Answered
P

2

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"
Perquisite answered 2/3, 2019 at 12:6 Comment(0)
R
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))
Rumple answered 2/3, 2019 at 12:8 Comment(1)
the first one works perfectly, thanks! (also wasn't aware of the existence lenghts)Perquisite
B
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" 
Bargainbasement answered 2/3, 2019 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.