How to change vector names of each list component

Viewed 88

I have a list:

alist <- list(x = c(1, 2, 3),
              y = c(4, 5, 6))

> alist 
$x 
[1] 1 2 3
    
$y 
[1] 4 5 6

I want to give names to each list component, to make it become:

> alist 
$x 
t1 t2 t3
1  2  3
            
$y 
t1 t2 t3
4  5  6

I tried to use lapply():

lapply(alist, function(x) names(x) <- c("t1","t2","t3"))

but the output is:

$x
[1] "t1" "t2" "t3"

$y
[1] "t1" "t2" "t3"

What is wrong here? How can I use lapply correctly here? Because I have a rather big list.

4 Answers

One option could be:

lapply(alist, setNames, c("t1","t2","t3"))

$x
t1 t2 t3 
 1  2  3 

$y
t1 t2 t3 
 4  5  6 

There is nothing wrong in the code except that the return should be the original data

lapply(alist, function(x) {
      names(x) <- c("t1","t2","t3");
       x})

The issue here is that, unless you include return() call at the end of the function, a function will return whatever the last result was. In your function as written, the last result was names(x), which returns the vector names.

To fix that, be sure that your anonymous function returns the actual vector as the last result:

alist <- list(x = c(1, 2, 3),
              y = c(4, 5, 6))

lapply(alist, function(x) {
  names(x) <- c("t1","t2","t3")
  x}
)
#> $x
#> t1 t2 t3 
#>  1  2  3 
#> 
#> $y
#> t1 t2 t3 
#>  4  5  6

# alternative:
lapply(alist, setNames, nm = c("t1","t2","t3"))
#> $x
#> t1 t2 t3 
#>  1  2  3 
#> 
#> $y
#> t1 t2 t3 
#>  4  5  6

Created on 2021-06-01 by the reprex package (v2.0.0)

In a very similar approach we could use map function from package purrr:

library(purrr)

alist %>%
  map(~ .x %>%
        set_names(c("t1", "t2", "t3")))

$x
t1 t2 t3 
 1  2  3 

$y
t1 t2 t3 
 4  5  6 
Related