Search code examples
rnames

How to name the elements of different R list elements?


I'm looking for an efficient way to name the elements of different list elements with one common vector of names. Suppose I have the following list:

# starting list
test <- list(a = c("name1", "name2", "name3"), 
             b = c(0.1, 0.2, 0.3), 
             c = c(TRUE, FALSE, TRUE))

which looks like

test

$a
[1] "name1" "name2" "name3"

$b
[1] 0.1 0.2 0.3

$c
[1]  TRUE FALSE  TRUE

I want to obtain something like

$b
name1 name2 name3 
  0.1   0.2   0.3 

$c
name1 name2 name3 
 TRUE FALSE  TRUE 

I know this can be obtained via something like...

names(test[[2]]) <- test$a
names(test[[3]]) <- test$a
test$a <- NULL

but this is only feasible if the number of list elements is small. I assume this can be obtained via one line of code. I have tried things like lapply(test, FUN = function(x) names(x)[] <- test$a) but this doesn't give the desired result.

Thank you in advance!


Solution

  • setNames is the equivalent to `names<-` for functional programming:

    lapply(test[-1], setNames, test$a)
    #$b
    #name1 name2 name3 
    #  0.1   0.2   0.3 
    #
    #$c
    #name1 name2 name3 
    # TRUE FALSE  TRUE