[R] using which to select range of values

David Winsemius dwinsemius at comcast.net
Thu Apr 22 17:48:25 CEST 2010


On Apr 22, 2010, at 11:39 AM, Steve Lianoglou wrote:

> Hi,
>
> On Thu, Apr 22, 2010 at 11:21 AM, Muhammad Rahiz
> <muhammad.rahiz at ouce.ox.ac.uk> wrote:
>> Hi all,
>>
>> I would like to get the array index for a range of values, say  0 <  
>> x < 1.5.
>> I'm wondering if there is an alternative for the following which  
>> I've done
>>
>> x0 <- rnorm(100)
>> x1 <- ifelse(x0 > 0 & x0 < 1.5,"t","f")
>> x2 <- which(x1=="t",arr.ind=TRUE)
>> x0[x2]
>
> Two things:
>
> 1. Not that it really matters, but why are you using arr.ind=TRUE when
> x0 is just a "normal" vector?
>
> 2. Just skip the middle-man creation of x1:
>
> R> x0 <- rnorm(100)
> R> x2 <- which(x0 > 0 & x0 < 1.5)
> R> x0[x2]
>
> Why not just skip the middle man (x1)?

Or just skip all the middle-men:

x0[ which(x0 > 0 & x0 < 1.5) ]

And further simplification with logical indexing:

x0[ x0 > 0 & x0 < 1.5 ]

-- 
David.

>
> -- 
> Steve Lianoglou
> Graduate Student: Computational Systems Biology
> | Memorial Sloan-Kettering Cancer Center
> | Weill Medical College of Cornell University
> Contact Info: http://cbio.mskcc.org/~lianos/contact
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list