Access and preserve list names in lapply function

前端 未结 6 1549
遇见更好的自我
遇见更好的自我 2020-12-01 01:33

I need to access list names inside the lapply function. I\'ve found some threads online where it\'s said I should iterate through the names of the list to be able to fetch e

6条回答
  •  [愿得一人]
    2020-12-01 02:04

    the setNames function is a useful shortcut here

    mylist <- list(a = TRUE, foo = LETTERS[1:3], baz = 1:5)
    n <- names(mylist)
    mynewlist <- lapply(setNames(n, n), function(nameindex) {mylist[[nameindex]]})
    

    which preserves the names

    > mynewlist
    $a
    [1] TRUE
    
    $foo
    [1] "A" "B" "C"
    
    $baz
    [1] 1 2 3 4 5
    

提交回复
热议问题