Another R tip. Use `seq_len()`

to avoid the backwards sequence trap.

Many R users use the “colon sequence” notation to build sequences. For example:

for(i in 1:5) { print(paste(i, i*i)) } #> [1] "1 1" #> [1] "2 4" #> [1] "3 9" #> [1] "4 16" #> [1] "5 25"

However, the colon notation can be unsafe as it does not properly handle the empty sequence case:

n <- 0 1:n #> [1] 1 0

Notice the above example built a reversed sequence, instead of an empty sequence.

This leads to the backwards sequence trap: writing code of the form “`1:length(x)`

” is often wrong. For example “`for(i in 1:length(x)) { statements involving x[[i]] }`

“, which will fail for length-zero `x`

.

To avoid this use `seq_len()`

:

seq_len(5) #> [1] 1 2 3 4 5 n <- 0 seq_len(n) #> integer(0)

“`integer(0)`

” is a length zero sequence of integers (not a sequence containing the value zero).