Access and preserve list names in lapply function

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

    I believe that lapply by default keeps the names attribute of whatever you are iterating over. When you store the names of myList in n, that vector no longer has any "names". So if you add that back in via,

    names(n) <- names(myList)
    

    and the use lapply as before, you should get the desired result.

    Edit

    My brains a bit foggy this morning. Here's another, perhaps more convenient, option:

    sapply(n,FUN = ...,simplify = FALSE,USE.NAMES = TRUE)
    

    I was groping about, confused that lapply didn't have a USE.NAMES argument, and then I actually looked at the code for sapply and realized I was being silly, and this was probably a better way to go.

提交回复
热议问题