Reputation: 25484
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)
Upvotes: 12
Views: 3121
Reputation: 25484
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)
Upvotes: 6
Reputation: 350
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))
Upvotes: 9
Reputation: 1383
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
Upvotes: 17