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

后端 未结 3 1375
走了就别回头了
走了就别回头了 2021-02-19 17:57

Imagine that I have the following list

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

Each element of the list has a name :

>          


        
3条回答
  •  孤城傲影
    2021-02-19 18:24

    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"    
    

提交回复
热议问题