[R] ifelse()

Martin Maechler maechler at stat.math.ethz.ch
Wed Mar 26 12:00:28 CET 2003


>>>>> "Jason" == Jason Turner <jasont at indigoindustrial.co.nz>
>>>>>     on Wed, 26 Mar 2003 22:49:27 +1200 writes:

    Jason> On Wed, Mar 26, 2003 at 11:20:04PM +1200, Ko-Kang
    Jason> Kevin Wang wrote:
    >> Hi,
    >> 
    >> I'm not sure if this can be done but..
    >> 
    >> I know that with ifelse() I can do something like:
    >> ifelse(x <= 3, 1, 2) to go through each element in my
    >> vector x, and if x_i <= 3 substitute the number with 1
    >> else with 2.  Essentially I'll get a vector with 2
    >> levels.
    >> 
    >> Can I tweak it so I can get 3-levels?  For example: if(x
    >> <= 3) then 1 elseif(3 < x <= 4) then 2 elseif(x > 4) then
    >> 3

    Jason> You can, like this (1 if zz < 5, 2 if 5 <= zz < 10, 3
    Jason> if zz >= 10)
    >> zz <- 1:20 ifelse(zz < 5, 1, ifelse(zz < 10, 2,3))
    Jason>  [1] 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3

Yes, but for cases like this (interval cutting),
the function
		cut()
will be much more efficient (and its call easier to read).
Martin



More information about the R-help mailing list