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

一世执手 提交于 2019-12-05 02:49:51

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"    

Assuming you meant for both elements of test to contain a 3-columned matrix, you can use mapply() and provide separately the list and the list's names:

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

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

  mapply(make_df, x = test, y = names(test), SIMPLIFY = FALSE)

which produces:

## $a
##   items type a
## 1     1    1 1
##
## $b
##   items type b
## 1     2    2 2

Update

To achieve the expected output you describe in your updated question:

test.names <- lapply(names(test), function(x) c("index", "type", x))
Map(setNames, test, test.names)

produces:

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

Based on the expected output showed

  make_attr_names <- function(x){
   x1 <- test[[x]]
   attr(x1, 'names') <- c('items','type', x)
   x1}
lapply(names(test), make_attr_names)  
 #[[1]]
 #    [,1] [,2] [,3]
 #[1,]    1    1    1
 #attr(,"names")
 #[1] "items" "type"  "a"    

 #[[2]]
 #    [,1] [,2] [,3]
 #[1,]    2    2    2
 #attr(,"names")
 #[1] "items" "type"  "b"  

Or based on the description

 make_df <- function(x){
       setNames(as.data.frame(test[[x]]), c('items', 'type', x))}
 lapply(names(test), make_df)
 #[[1]]
 # items type a
 #1     1    1 1

 #[[2]]
 #  items type b
 #1     2    2 2
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!