[R] how to get empty sequence for certain bounds
Marc Schwartz
marc_schwartz at comcast.net
Wed Nov 15 18:37:04 CET 2006
On Wed, 2006-11-15 at 11:35 -0500, Tamas K Papp wrote:
> Hi,
>
> I have encountered this problem quite a few times and thought I would
> ask.
>
> Let's say that I have two endpoints, a and b, which are integers. If
> a <= b, I would like to get a:b, but if a > b, then numeric(0), for
> example:
>
> myseq(3,5) => 3:5
> myseq(3,3) => 3
> myseq(3,2) => numeric(0)
>
> The operator : just gives decreasing sequences in the latter case, and
> I could not coax seq into doing this either (of course the
> documentation is correct, it never claims that I could). Should I
> just write my own function, or is there a standard R way to do this?
>
> Thanks,
>
> Tamas
seq(a, b, length = ifelse(a <= b, b - a + 1, 0))
Thus:
a <- 3
b <- 5
> seq(a, b, length = ifelse(a <= b, b - a + 1, 0))
[1] 3 4 5
a <- 5
b <- 3
> seq(a, b, length = ifelse(a <= b, b - a + 1, 0))
integer(0)
However, is that better than:
a <- 3
b <- 5
> if (a <= b) a:b else numeric(0)
[1] 3 4 5
a <- 5
b <- 3
> if (a <= b) a:b else numeric(0)
numeric(0)
?
Of course, you could define your own operator:
"%:%" <- function(a, b) {if (a <= b) a:b else numeric(0)}
a <- 3
b <- 5
> a %:% b
[1] 3 4 5
a <- 5
b <- 3
> a %:% b
numeric(0)
HTH,
Marc Schwartz
More information about the R-help
mailing list