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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With