How to get the name of each element of a list using lapply()?

PAC picture PAC · Jun 24, 2015 · Viewed 21.3k times · Source

Imagine that I have the following list

> test <- list("a" = 1, "b" = 2)

Each element of the list has a name :

> names(test)

Now, I want to extract that name using lapply() because I want to use it in a new function which will be called using lapply. I just don't know how to extract the name of each element.

I've tried using deparse() and substitute() but the outcome is weird :

> lapply(test, function(x) {deparse(substitute(x))})
$a
[1] "X[[i]]"

$b
[1] "X[[i]]"

Does anyone has a clue ?

Precision :

I want to do something like this : I have a list which is like test :

> test <- list("a" = matrix(1, ncol = 3), "b" = matrix(2, ncol = 3))

I want to apply a function to that list which transform the data inside each element and give a specific name for each column :

make_df <- function(x) {
  output <- data.frame(x)
  names(output) <- c("items", "type", NAME_OF_X)
  return(output)
}
lapply(test, make_df)

The expected output is :

> test
$a
     [,1] [,2] [,3]
[1,]    1    1    1
attr(,"names")
[1] "index" "type"  "a"    

$b
     [,1] [,2] [,3]
[1,]    2    2    2
attr(,"names")
[1] "index" "type"  "b"    

I don't know how I can get the name of the element to give a name to my third column.

Answer

thie1e picture thie1e · Dec 7, 2016

Here's a solution using purrr. It seems to run faster than the solution by aaronwolden but slower than akrun's solution (if that's important):

library(purrr)
map2(test, names(test), function(vec, name) {
    names(vec) <- c("index", "type", name)
    return(vec)
})

$a
     [,1] [,2] [,3]
[1,]    1    1    1
attr(,"names")
[1] "index" "type"  "a"    

$b
     [,1] [,2] [,3]
[1,]    2    2    2
attr(,"names")
[1] "index" "type"  "b"