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 each list element name in my function:
> n = names(mylist) > mynewlist = lapply(n, function(nameindex, mylist) { return(mylist[[nameindex]]) }, mylist) > names(mynewlist) NULL > names(mynewlist) = n
The problem is that mynewlist loses the original mylist indexes and I have to add that last names() assignment to restore them.
Is there a way to give an explicit index name to each element returned by the lapply function? Or a different way to make sure mynewlist elements have the correct index names set? I feel mynewlist index names could be wrong if lapply does not return the list elements in the same order than mylist.
lapply returns a list of the same length as X , each element of which is the result of applying FUN to the corresponding element of X .
The lapply() function in R can be used to apply a function to each element of a list, vector, or data frame and obtain a list as a result. The sapply() function can also be used to apply a function to each element of a list, vector, or data frame but it returns a vector as a result.
The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list.
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.
the setNames
function is a useful shortcut here
mylist <- list(a = TRUE, foo = LETTERS[1:3], baz = 1:5) n <- names(mylist) mynewlist <- lapply(setNames(n, n), function(nameindex) {mylist[[nameindex]]})
which preserves the names
> mynewlist $a [1] TRUE $foo [1] "A" "B" "C" $baz [1] 1 2 3 4 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With