1

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?

Community
  • 1
  • 1
Danny
  • 448
  • 3
  • 15
  • 1
    Possible duplicate of [Access lapply index names inside FUN](http://stackoverflow.com/questions/9950144/access-lapply-index-names-inside-fun) – Mike H. Apr 20 '17 at 20:11
  • Thanks, that approach looks like it would be faster. I don't think this is a duplicate question though because I'm not asking for a way to do it (I already know slow ways). I want to know the fastest way and there's no speed comparisons for the approach in the accepted answer. – Danny Apr 21 '17 at 13:06

1 Answers1

1

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.

Gladwell
  • 328
  • 3
  • 10
  • Thanks, I hadn't thought of storing them separately. The functions I want to use aren't vectorised so I still need a loop/apply, but I assume this is still the faster implementation? – Danny Apr 21 '17 at 13:02
  • Hard to say without knowing what you want to do. Either update your original post with full details or post a separate question about whether your loops can be vectorised. I haven't seen many operations that can't, in some way, be vectorised. – Gladwell Apr 21 '17 at 16:48