Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

name character vectors with same name of list

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"
like image 791
likeeatingpizza Avatar asked Mar 02 '19 12:03

likeeatingpizza


2 Answers

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" 
like image 36
Moody_Mudskipper Avatar answered Sep 20 '22 02:09

Moody_Mudskipper


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))
like image 55
akrun Avatar answered Sep 18 '22 02:09

akrun