[R] Testing for Inequality à la "select case"

Stavros Macrakis macrakis at alum.mit.edu
Mon Mar 16 02:46:59 CET 2009

On Sun, Mar 15, 2009 at 6:34 PM, diegol <diegol81 at gmail.com> wrote:
>> If you'd do it element-by-element in Excel, why not do it
>> element-by-element in R?
> Well, actually I was hoping for a vectorized solution so as to avoid
> looping.

That's what I meant by element-by -element. A vector in R corresponds
to a row or a column in Excel, and a vector operation in R corresponds
to a row or column of formulae, e.g.

     A      B       C
1)  5      10      a1+b1  (= 15)
2)  3       2       a2+b2  (= 5)

A <- c(5,3)
B <- c(10,2)
C <- A + B

> I need to use this formula on rather lengthy vectors and I wanted
> to put R's efficiency to some good use....

> I would however use max instead of pmax, since the argument for mr() must be
> a vector of length 1.

max and pmax are equivalent in this case.  I just use pmax as my
default because it acts like other arithmetic operators (+, *, etc.)
which perform pointwise (element-by-element) operations.

I do wonder if there isn't a simpler/cleaner/faster way to write
which(x<=range)[1], then again in most applications it is plenty fast


More information about the R-help mailing list