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

后端 未结 3 1393
走了就别回头了
走了就别回头了 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:19

    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"  
    

提交回复
热议问题