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.
Just write your own custom
lapply
functionThen use like this:
My answer goes in the same direction as Tommy's and caracals, but avoids having to save the list as an additional object.
Result:
This gives the list as a named argument to FUN (instead to lapply). lapply only has to iterate over the elements of the list (be careful to change this first argument to lapply when changing the length of the list).
Note: Giving the list directly to lapply as an additional argument also works:
I've had the same problem a lot of times... I've started using another way... Instead of using
lapply
, I've started usingmapply
Just loop in the names.
You could try using
imap()
frompurrr
package.From the documentation:
So, you can use it that way :
Which will give you the following result:
Unfortunately,
lapply
only 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
lapply
over the indices ofx
, but also pass inx
and the names ofx
. As you can see, the order of the function arguments can be anything -lapply
will pass in the "element" (here the index) to the first argument not specified among the extra ones. In this case, I specifyy
andn
, so there's onlyi
left...Which produces the following:
UPDATE Simpler example, same result:
Here the function uses "global" variable
x
and extracts the names in each call.