The following works: socstat=rep(c("A","B","D","E"),each=100) male=rep(1:4,100) socstat2=ifelse(socstat=="B"&male==4,"C",socstat)
Therefore, your code should work if it were the code you want (in other words, it's a logic not a coding problem). Your mistake is that you recode ALL social statuses of observations that are not "B" AND MALE!=4 into Bs. That is, all observations with social status not B (A,D,E,F,G,H,I,J...) are recoded into Bs. That is certainly not what you want. I think what you want is: data$SOCIAL_STATUS<-ifelse(data$SOCIAL_STATUS=="B" & data$MALE>4, "C", data$SOCIAL_STATUS) Right? Daniel ------------------------- cuncta stricte discussurus ------------------------- -----Ursprüngliche Nachricht----- Von: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] Im Auftrag von Mark Na Gesendet: Tuesday, June 23, 2009 6:33 PM An: r-help@r-project.org Betreff: [R] Problem with ifelse statement 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 ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.