Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

r - Access and preserve list names in lapply function

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...