Index iteration idiom

Viewed 573

The following code is commonly seen on SO when it comes to iterating over the index values of a collection:

for (i in 1:length(x)) {
  # ...
}

The code misbehaves when the collection is empty because 1:length(x) becomes 1:0 which gives i the values 1 and 0.

iterate <- function(x) {
    for (i in 1:length(x)) {
      cat('x[[', i, ']] is', x[[i]], '\n')
    }
}

> iterate(c(1,2,3))
x[[ 1 ]] is 1 
x[[ 2 ]] is 2 
x[[ 3 ]] is 3 

> iterate(c())
x[[ 1 ]] is  
x[[ 0 ]] is

I recall seeing an elegant idiom for defining a sequence that has no elements when x is empty but I cannot remember it. What idiom do you use?

1 Answers
Related