James
James

Reputation: 55

ifelse in R: alternatives to nesting

I have written a series of ifelse statements that create a new column in a data frame. Example:

rf$rs.X<- ifelse(rf$chl==0 & rf$dm=="y" & rf$gdr=="m" & rf$smk=="n" & rf$age>=70 & rf$sbp>=160, ">=40%", NA)

When I run additional ifelse statements, they overwrite the previous one, because I map it to the same new column in the data frame (i.e. all my ifelse statements begin with the same rf$rs.X).

I know that for each statement I could specify a new column to be created, but I have 68 ifelse statements and I do not want a new column for each: I want a single new column.

To work around this I tried nesting all 68 ifelse statements but it doesn't seem to work (when I try to run it I get a blue plus sign (+)). After reading on here, it seems there is a limit to nesting (n=50).

So, for a series of ifelse statements, how can I get all the outputs to the same column in a data frame, with out the ifelse statement overwriting the previous one?

Thanks!

Upvotes: 0

Views: 804

Answers (1)

IRTFM
IRTFM

Reputation: 263481

I would have written it like this:

rf$rs.X<- with( rf, ifelse(chl==0 & dm=="y" & gdr=="m" &
                           smk=="n" & age>=70 & sbp>=160,    ">=40%", NA)

Then the next one (say for the low sbp cases, could have the rs.X value as the alternative:

rf$rs.X<- with( rf, ifelse(chl==0 & dm=="y" & gdr=="m" &
                           smk=="n" & age>=70 & sbp < 160,    "30-39%", rs.X)

So that way the value is not overwritten for the non-qualifying rows.

Upvotes: 1

Related Questions