0

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!

James
  • 55
  • 1
  • 5
  • 5
    Isn't it easier with a lookup table? –  Jan 13 '16 at 13:15
  • Yes, sorry that was a transposition error. In the actual code I have `rf$chl==0` – James Jan 13 '16 at 13:20
  • 5
    Could you give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610)? – Jaap Jan 13 '16 at 13:23
  • Some inspiration: [one](http://stackoverflow.com/questions/33314731/how-to-rename-levels-in-an-r-data-table-from-another-data-table/33315640#33315640) and [two](http://stackoverflow.com/questions/33416084/indexing-sequence-chunks-using-data-table/33421100#33421100) – Jaap Jan 13 '16 at 13:30
  • 1
    What about writing function with `else if ` statements and `apply ` it to each row in your data – Volodymyr Jan 13 '16 at 14:54

1 Answers1

1

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.

IRTFM
  • 258,963
  • 21
  • 364
  • 487