'Sequence construction that creates an empty sequence if lower is greater than upper bound

More than once the "cleverness" of R's seq function has hit me badly in the corner case when lower == upper - 1:

> 1:0
[1] 1 0
> seq(1, 0)
[1] 1 0
> seq(1, 0, 1)
Error in seq.default(1, 0, 1) : wrong sign in 'by' argument

I'm not asking for the reasons of this odd behavior -- I assume it's now just a legacy that we have to live with. Instead, I'd like to know if any package implements a seq operator that returns an empty sequence in this case, like the following:

safe.seq.int <- function(from, to, by=1) {
  if (from > to) integer(0) else seq.int(from, to, by)
}

> safe.seq.int(1, 0)
integer(0)


Solution 1:[1]

It's good practice to use seq_len(n) instead of 1:n for exactly this reason - if n=0 then you get an empty sequence rather than c(1,0).

Hope this helps

Solution 2:[2]

It's very unfortunate that both : operator and seq() function can't handle this case. The best answer I have found by far is the following:

seq(a,b,length = max(0,b-a+1))

Solution 3:[3]

The rlang package implements seq2():

rlang::seq2(3, 5)
#> [1] 3 4 5
rlang::seq2(3, 3)
#> [1] 3
rlang::seq2(3, 2)
#> integer(0)

Created on 2022-04-20 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim P
Solution 2 Ash
Solution 3