Access and preserve list names in lapply function

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

    Also building on @joran's answer, you can write a wrapper function that preserves object attributes such as below:

    lapply_preserve_names <- function(list, fun){
      lapply(seq_along(list), function(i) {
        obj = list[i]
        names(obj) = names(list)[i]
        fun(obj)
      })
    }
    

    then instead of using lapply, simply use lapply_preserve_names(your_list, function)

提交回复
热议问题