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

Stavros Macrakis macrakis at alum.mit.edu
Sun Mar 15 21:44:48 CET 2009


On Sun, Mar 15, 2009 at 4:12 PM, diegol <diegol81 at gmail.com> wrote:
> ...This could be done in Excel much tidier in my opinion (especially the
> range_aux part), element by element (cell by cell)...

If you'd do it element-by-element in Excel, why not do it
element-by-element in R?

Create a table with the limits of the ranges

    range= c(20,100,250,700,1000,Inf)*1000

and then find the index of the appropriate case using something like

    idx <- which(x<=range)[1]

Then the formula becomes simply

    pmax( x*perc[idx], min[idx] )

Putting it all together:

mr <-
  local({
    # Local constants
    range= c(20,100,250,700,1000,Inf)*1000
    perc = c(65,40,30,25,20,0)/100
    min =  c(0,14,40,75,175,250)*1000

    function(x)
      { idx <- which(x<=range)[1]
        pmax( x*perc[idx], min[idx] )
      }
  })

Make sense?

          -s




More information about the R-help mailing list