Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access and preserve list names in lapply function

Tags:

r

lapply

names

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.

like image 623
Robert Kubrick Avatar asked Feb 27 '12 17:02

Robert Kubrick


People also ask

Does Lapply return a list?

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 .

What is the difference between Lapply and Sapply in R?

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.

How do I add names to a list in R?

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.


2 Answers

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.

like image 61
joran Avatar answered Oct 08 '22 21:10

joran


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 
like image 44
Brian Diggs Avatar answered Oct 08 '22 21:10

Brian Diggs