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

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

    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
    

提交回复
热议问题