2

I want to loop through a list and work with its nth element, but the list can be empty:

l <- list()
for(i in 1:length(l)) a <- l[[i]]

If the list has 1 element, everything is fine. But if the list is empty, length(l) equals to zero, so the loop will try to run twice and count down i from 1 to 0. This throws an error, as l[[1]] doesn't exist:

> Error in l[[i]] : subscript out of bounds

Is there a better way to skip the for loop than checking if length(l) is bigger than zero?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
Smon
  • 45
  • 9

1 Answers1

8

You've stumbled across a "best practice" lesson in R. Generally, people recommend that you write for loops as

for (i in seq_along(obj))

rather than

for (i in 1:length(obj))

for precisely this reason. seq_along(list()) will return integer(0), skipping the loop entirely.

There is also the option of seq_len if you only have the length, which may be zero:

for (i in seq_len(x))

where seq_len() will do the right thing when x = 0 and will return an error if x <0, which is usually what you want.

joran
  • 169,992
  • 32
  • 429
  • 468