klo
klo

Reputation: 189

ifelse statement for more than two conditions

I know many question are asked about ifelse, but I searched and tried a lot but no success, therefore I'm posting question here.

I have a data frame of 10k participants with 8 variables, each variable is coded 0, 1, 9 and NA. I would like to create one variable to summarize all 8 variables.

The condition I want to create is: if one from 8 variables has the value 1, then new variable should be 1, if one has a 9, then return 9, else (all in row are NA or other) return 0.

The code i created is this, but get only 1 and NA:

z = with(dt, ifelse(var.1==1|var.2==1|var.3==1|var.4==1|
var.5==1|var.6==1|var.7==1|var.8==1, 1, ifelse(var.1==9|var.2==9|var.3==9|var.4==9|
var.5==9|var.6==9|var.7==9|var.8==9, 9, 0)))

Thank you.

Upvotes: 1

Views: 2832

Answers (1)

IRTFM
IRTFM

Reputation: 263301

Try this (untested code in the absence of a data example):

 ifelse( rowSums(dt[ , c("var.1","var.2", "var.3", "var.4", "var.5", "var.6", "var.7", 
                         "var.8")]==1, na.rm=TRUE), 1, 
       ifelse(  rowSums(dt[ , c("var.1","var.2", "var.3", "var.4", "var.5", 
                                 "var.6", "var.7", "var.8")]==9, na.rm=TRUE) , 
                 9, 0))

There is an implicit coercion of the value 0 to false by the ifelse calls and any value other than 0 is TRUE. The na.rm=TRUE keeps the sums from being NA. I suppose you could get into problems if all of the values in a row were NA.

Upvotes: 2

Related Questions