Is there a way to get the list index name in my lapply() function?
n = names(mylist)
lapply(mylist, function(list.elem) { cat("What is the name of this list element?\n" })
I asked before if it’s possible to preserve the index names in the lapply() returned list, but I still don’t know if there is an easy way to fetch each element name inside the custom function. I would like to avoid to call lapply on the names themselves, I’d rather get the name in the function parameters.
Unfortunately,
lapplyonly gives you the elements of the vector you pass it.The usual work-around is to pass it the names or indices of the vector instead of the vector itself.
But note that you can always pass in extra arguments to the function, so the following works:
Here I use
lapplyover the indices ofx, but also pass inxand the names ofx. As you can see, the order of the function arguments can be anything –lapplywill pass in the “element” (here the index) to the first argument not specified among the extra ones. In this case, I specifyyandn, so there’s onlyileft…Which produces the following:
UPDATE Simpler example, same result:
Here the function uses “global” variable
xand extracts the names in each call.