ifelse() is the most direct way, but cut() might be easier, especially for
the case of general break points. However cut uses intervals that include
the right-hand point and exclude the left ("0.5+ thru 1.5"), whereas you
want the opposite. One trick is to apply cut to the negative of the data and
reverse the order of the levels.
> x <- seq(0,2,0.1)
> x
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7
1.8 1.9 2.0
> ifelse(x<0.5,0,ifelse(x<1.5,1,2))
[1] 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
> cut(x,breaks=c(-Inf,0.5,1.5,Inf),factor=T)
[1] -Inf+ thru 0.5 -Inf+ thru 0.5 -Inf+ thru 0.5 -Inf+ thru 0.5 -Inf+ thru
0.5 -Inf+ thru 0.5 0.5+ thru 1.5 0.5+ thru 1.5
[9] 0.5+ thru 1.5 0.5+ thru 1.5 0.5+ thru 1.5 0.5+ thru 1.5 0.5+ thru
1.5 0.5+ thru 1.5 0.5+ thru 1.5 0.5+ thru 1.5
[17] 1.5+ thru Inf 1.5+ thru Inf 1.5+ thru Inf 1.5+ thru Inf 1.5+ thru
Inf
> c(0,1,2)[cut(x,breaks=c(-Inf,0.5,1.5,Inf),factor=T)] # using a factor as
an index
[1] 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 # not quite
what you want
> rev(c(0,1,2))[cut(-x,breaks=-rev(c(-Inf,0.5,1.5,Inf)),factor=T)]
[1] 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 # this is
what you want
Nick Ellis
CSIRO Marine Research mailto:Nick.Ellis@csiro.au
PO Box 120 ph +61 (07) 3826 7260
Cleveland QLD 4163 fax +61 (07) 3826 7222
Australia http://www.marine.csiro.au
> -----Original Message-----
> From: Frank Lawrence [mailto:Cougar@psu.edu]
> Sent: Friday, March 21, 2003 3:35 AM
> To: s-news@lists.biostat.wustl.edu
> Subject: [S] recode
>
>
> I would like to know how to quickly recode multiple variables. In one
> problem I have, I need to recode the data in a 600 x 200 data
> frame so that
> values less than 0.5 are scored 0, those equal to or greater
> than 1.5 are
> scored 2, and those in between are scored 1. Using loops
> seems to take a
> very long time. Is there a more efficient way to accomplish
> the recode?
> WIN 2k, Splus 6.1
>
>
> Respectfully,
> Frank R. Lawrence
>
> --------------------------------------------------------------------
> This message was distributed by s-news@lists.biostat.wustl.edu. To
> unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
> the BODY of the message: unsubscribe s-news
>
|