Reputation: 488
What is the most efficient way to iterate over a list in R if I need to access both the names and values of items in the list separately?
If I try something like:
lst <- list(a = 1, b = 2)
for(i in lst) {
# ...
}
Then I only get the value and can't see a way to access the name.
So currently I do:
lst <- list(a = 1, b = 2)
for(i in names(lst)) {
# something with i
# something with lst[[i]]
}
But this seems terribly inefficient to me since I access each item from the list by its name which I assume is slow. To avoid that I could do:
lst <- list(a = 1, b = 2)
for(i in seq_along(lst)) {
# something with names(lst)[i]
# something with lst[[i]]
}
But I'm not sure if this is any more or less efficient.
Is there a more efficient way than either of these? And if not, which of these should I be using?
Edit:
The answer to this question and @Gladwell gives another suggestion:
lst <- list(a = 1, b = 2)
names_lst <- names(lst)
for(i in seq_along(lst)) {
# something with names_lst[i]
# something with lst[[i]]
}
Is this the fastest option? Can it be improved in any way?
Upvotes: 1
Views: 560
Reputation: 328
The fastest way is likely to do the two calls separately and store them to use vectorised functions for whatever you want to do.
tmpNames <- names(lst)
tmpValues <- as.vector(unlist(lst))
e.g.
paste0(tmpNames, tmpValues)
is about 2-3 times faster than your current implementation.
Upvotes: 1