[R] Find all numbers in a certain interval

Greg Snow Greg.Snow at imail.org
Tue Dec 16 23:42:20 CET 2008


Here are a couple of function definitions that may be more intuitive for some people (see the examples below the function defs).  They are not perfect, but my tests showed they work left to right, right to left, outside in, but not inside out.

`%<%` <- function(x,y) {
        xx <- attr(x,'orig.y')
        yy <- attr(y,'orig.x')

        if(is.null(xx)) {
                xx <- x
                x <- rep(TRUE, length(x))
        }
        if(is.null(yy)) {
                yy <- y
                y <- rep(TRUE, length(y))
        }

        out <- x & y & (xx < yy)
        attr(out, 'orig.x') <- xx
        attr(out, 'orig.y') <- yy

        out
}

`%<=%` <- function(x,y) {
        xx <- attr(x,'orig.y')
        yy <- attr(y,'orig.x')

        if(is.null(xx)) {
                xx <- x
                x <- rep(TRUE, length(x))
        }
        if(is.null(yy)) {
                yy <- y
                y <- rep(TRUE, length(y))
        }

        out <- x & y & (xx <= yy)
        attr(out, 'orig.x') <- xx
        attr(out, 'orig.y') <- yy

        out
}




x <- -3:3

 -2 %<% x %<% 2
c( -2 %<% x %<% 2 )
x[ -2 %<% x %<% 2 ]
x[ -2 %<=% x %<=% 2 ]


x <- rnorm(100)
y <- rnorm(100)

x[ -1 %<% x %<% 1 ]
range( x[ -1 %<% x %<% 1 ] )


cbind(x,y)[ -1 %<% x %<% y %<% 1, ]
cbind(x,y)[ (-1 %<% x) %<% (y %<% 1), ]
cbind(x,y)[ ((-1 %<% x) %<% y) %<% 1, ]
cbind(x,y)[ -1 %<% (x %<% (y %<% 1)), ]
cbind(x,y)[ -1 %<% (x %<% y) %<% 1, ] # oops

Hope this helps,

--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Antje
> Sent: Tuesday, December 16, 2008 3:09 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Find all numbers in a certain interval
>
> Hi all,
>
> I'd like to know, if I can solve this with a shorter command:
>
> a <- rnorm(100)
> which(a > -0.5 & a < 0.5)
>
> # would give me all indices of numbers greater than -0.5 and smaller
> than +0.5
>
> I have something similar with a dataframe and it produces sometimes
> quite long
> commands...
> I'd like to have something like:
>
> which(within.interval(a, -0.5, 0.5))
>
> Is there anything I could use for this purpose?
>
>
> Antje
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list