[R] Nested ifelse - is there a better way?
Charles C. Berry
cberry at tajo.ucsd.edu
Thu Jan 13 21:35:57 CET 2005
Jeff> I'm interested in finding a better way to add a column to a data
Jeff> frame when calculating the new column requires more than one
Jeff> conditional.
[description of doing this with lots of ifelse's deleted]
Jeff
If all you are doing is slicing one quantitative variable into categories,
then see
?cut
and
?findInterval
---------
If you need to use multiple variable to define the splits, you might
construct an index using a 'mixed radix positional numbering system' (I
suggest you google that term if it isn't familiar)
As an example if you have two variables (x and y,say) coded as (0,1,2) and
(0,1,2,3,4), then
z <- x * ( max(y) + 1 ) + y
gives you z with categories (0,...,14). Extended to three or more
variables, you need to do some nested multiplications.
Alternatively, you can use tapply to get this type of result
z <- tapply( x, list( x, y ) )
but here the categories will be numbered from 1. Some care may be needed
to be sure that the category numbers are what you wanted.
----------
Subscripting can be used to combine categories
Here I combine 6 and 7, 8 and 9, and 14 and 15:
z.recode <- c(1,2,3,4,5,6,6,7,7,8,9,10,11,12,12)
z2 <- z.recode[ z ]
and do not miss out on
?levels
as "levels(x) <- value" will do the same when x is a factor.
HTH,
Chuck
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://hacuna.ucsd.edu/members/ccb.html La Jolla, San Diego 92093-0717
More information about the R-help
mailing list