Access and preserve list names in lapply function

前端 未结 6 1552
遇见更好的自我
遇见更好的自我 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 01:41

    imap() from the purrr package is nice for your problem.

    library(purrr)
    mylist <- list(foo1=1:10,foo2=11:20)
    imap(mylist, function(x, y) mean(x)) ## x is the value, y is the name
    

    or you can use a more compact version of imap:

    imap(mylist, ~ mean(.x))
    

    Note that you can use variations of imap_xxx depending on the type of vector you want:

    imap_dbl(mylist, ~ mean(.x)) ## will return a named numeric vector. 
    

提交回复
热议问题