Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

sequence

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)
like image 925
krlmlr Avatar asked Jun 06 '12 20:06

krlmlr


2 Answers

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

like image 182
Tim P Avatar answered Nov 05 '22 10:11

Tim P


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))
like image 31
Ash Avatar answered Nov 05 '22 09:11

Ash