[R] Problem with ifelse statement

Mark Na mtb954 at gmail.com
Wed Jun 24 00:32:36 CEST 2009


Hi R-helpers,

I am trying to use this ifelse statement to recode a variable:
> data$SOCIAL_STATUS<-ifelse(data$SOCIAL_STATUS=="B" & data$MALE>4, "C", "B")

(i.e., if social status is B and there are more than 4 males, then
recode social status to C; otherwise, leave it B)

But, it's not working. See the below R output. Notice that there were
71 "B" observations before the re-code but 2098 "B" observations after
the re-code. The only thing my code should do is REDUCE the number of
"B" observations, not increase them.

Can anyone see what I'm doing wrong? Thanks!

Thanks, Mark Na


> str(data)
'data.frame':   2100 obs. of  13 variables:
 $ DATE           :Class 'Date'  num [1:2100] 14399 14399 14399 14399 14399 ...
 $ OBS            : Factor w/ 7 levels "AJG","LEB","MB",..: 3 3 3 3 3
3 3 3 3 3 ...
 $ POND_ID        : Factor w/ 118 levels "1","10","100",..: 86 86 86
86 86 86 86 86 86 86 ...
 $ STATUS         : num  1 1 1 1 1 1 1 1 1 1 ...
 $ SPECIES        : Factor w/ 25 levels "AGWT","AMAV",..: 16 16 12 12
4 7 7 7 7 3 ...
 $ SOCIAL_STATUS  : Factor w/ 9 levels "","A","B","D",..: 5 2 5 2 5 5
5 5 2 8 ...
 $ COUNT_OF_GROUPS: num  1 1 1 1 1 3 3 3 1 2 ...
 $ MALE           : num  1 1 1 1 1 1 1 1 1 0 ...
 $ FEMALE         : num  1 0 1 0 1 1 1 1 0 0 ...
 $ NOSEX          : num  0 0 0 0 0 0 0 0 0 2 ...
 $ UPLAND         : num  0 0 0 0 0 0 0 0 0 0 ...
 $ TAG            : num  0 0 0 0 0 0 0 0 0 0 ...
 $ COMMENT        : chr  "" "" "" "" ...


> length(which(data$SOCIAL_STATUS=="B"))
[1] 71

> data$SOCIAL_STATUS<-ifelse(data$SOCIAL_STATUS=="B" & data$MALE>4, "C", "B")

> length(which(data$SOCIAL_STATUS=="B"))
[1] 2098




More information about the R-help mailing list