Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index iteration idiom

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?

like image 252
Sim Avatar asked Aug 10 '12 02:08

Sim


1 Answers

Either seq or seq_along give you something more reasonable when your object of interest is empty.

> x <- NULL
> seq(x)
integer(0)
> seq_along(x)
integer(0)
> x <- rnorm(5)
> seq(x)
[1] 1 2 3 4 5
> seq_along(x)
[1] 1 2 3 4 5
like image 198
Dason Avatar answered Nov 17 '22 02:11

Dason