[R] Searching for specific values in a matrix

Steve Lianoglou mailinglist.honeypot at gmail.com
Tue Jul 21 21:10:04 CEST 2009


> I am a bit confused as to what the following command does:
> evens <- df$nums %% 2 == 0

It returns a logical vector (I'm calling this an "indexing vector")  
that is TRUE where df$nums %% 2 == 0 (%% is modulo division, and 4 mod  
2 == 0 -- so it's a test for "being even")

> In my matrix example, let's say I am looking for the variable(s) BC  
> and I want R to return all the rows with that value...

You "just" have to setup a suitable test and build an "indexing"  
vector to select the appropriate rows -- or use the subset function  
(see ?subset).

If it's still confusing to you, please create a trivial example  
data.frame and send it back to the list along with things you'd like  
to "find", so we can give you concrete examples on different ways you  
can find what you need.

> or If I want a value such as 33.543.  How would I get it to do  
> that?   Just a single value in the latter case.  I have already  
> converted it to a data frame.

Be careful when searching for doubles/floats as sometimes you'll miss  
what you're looking for if you are using exact matches (ie something  
== something.else) ... I have an almost.equals function in my "bag of  
utilities" that I'd probably use for stuff like this:

almost.equal <- function(x, y, eps=0.000001) {
   abs(x - y) < eps
}

'%~%' <- function(x, y) almost.equal(x, y))

R> x <- rnorm(1000, sd=.0001)
R> sum(x %~% 0)
## Equivalently: sum(almost.equal(x, 0))
[1] 8

R> sum(x == 0)
[1] 0

Summing over a logical vector treats the TRUE values as 1 and FALSE  
values as 0.

HTH,
-steve

--
Steve Lianoglou
Graduate Student: Physiology, Biophysics and Systems Biology
Weill Medical College of Cornell University

Contact Info: http://cbio.mskcc.org/~lianos/contact




More information about the R-help mailing list