[R] How to fix my nested conditional IF ELSE code?

David Winsemius dwinsemius at comcast.net
Mon Jun 15 01:53:10 CEST 2009


On Jun 14, 2009, at 6:33 PM, Chuck Cleland wrote:

> On 6/14/2009 6:18 PM, Mark Na wrote:
>>
>> Here's what I need to do (dummy example, my data are more  
>> complicated):
>>
>> If type = A or B or C
>>     and status = a then count = 1
>>     and status = b then count = 2
>>     and status = c then count = 3
>>
>> Else if type = D or E or F
>>     and status = a then count = 9
>>     and status = b then count = 8
>>     and status = c then count = 7
>>
>> End
>>
>> Seems simple when I write it like that, but the R code is escaping  
>> me.
>
> mydf <- data.frame(type = sample(LETTERS[1:6], 40, replace=TRUE),
>                   status = sample(letters[1:3], 40, replace=TRUE))
>
> mydf$count <- with(mydf,
>                ifelse(type %in% c('A','B','C') & status == 'a', 1,
>                ifelse(type %in% c('A','B','C') & status == 'b', 2,
>                ifelse(type %in% c('A','B','C') & status == 'c', 3,
>                ifelse(type %in% c('D','E','F') & status == 'a', 9,
>                ifelse(type %in% c('D','E','F') & status == 'b', 8,
>                ifelse(type %in% c('D','E','F') & status == 'c', 7,
> NA)))))))

Or more compactly and perhaps easier to maintain since you are  
approaching the nesting limits of ifelse and the OP said he had a more  
complex operation to perform:

library(car)
mydf$count <- with(mydf, ifelse( type %in% c('A','B','C'),
                              recode( status, " 'a'=1; 'b'=2; 'c'=3 ",  
FALSE),
                              ifelse( type %in% c('D','E','F') ,
                                   recode( status, " 'a'=9; 'b'=8;  
'c'=7 ", FALSE),
                                   NA)  )  )

>

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list