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)
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
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))
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