0

New to SO. Don't kill me. I'm trying to figure out how to use 'ifelse' statements to add columns to a dataframe, based on a quantitative criteria related to a different column.

DTzips2[, politics := ifelse(pctr08zip > 0 & pctr08zip <= 0.33, "Liberal"),
                       ifelse(pctr08zip > 0.33 & pctr08zip <= 0.67, "Moderate"),
                              ifelse(pctr08zip > 0.67 & pctr08zip <=1, "Conservative")]


Error I've been getting is 'Provide either 'by' or 'keyby' but not both'. They also don't like the comma after 0.33. Help?

Shawn Danino
  • 19
  • 2
  • 4
  • 1
    Try typing `?cut`. `elif` does not exist in R. – Frank Jul 31 '17 at 16:50
  • sorry, copied the wrong code. With 'ifelse' statements now. – Shawn Danino Jul 31 '17 at 16:56
  • Ok, the parentheses are placed incorrectly, since `ifelse` takes three arguments but you chronically use `)` after only two. Anyways, I guess `cut` does it. Try typing `example(cut)` if you for some reason don't want to read the docs. – Frank Jul 31 '17 at 17:04
  • Nested `ifelse` needs to actually be **nested**. `cut` is better for this anyway, but syntactically your problem is that you have `ifelse(condition1, yes-result), ifelse(condition2, yes-result), ...`, but what you should have is `ifelse(condition, yes = yes-result, no = ifelse(condition2, yes = yes2-result, no = no2))`. – Gregor Thomas Jul 31 '17 at 17:08
  • 1
    So in your case, we could simplify (assuming is between 0 and 1): `ifelse(pctr08zip <= 0.33, 'Liberal', ifelse(pctr08zip <= 0.67, 'Moderate', 'Conservative))`. Or using cut: `cut(pctr08zip, breaks = c(0, 0.33, 0.67, 1), labels = c("Liberal", "Moderate", "Conservative")`. – Gregor Thomas Jul 31 '17 at 17:13

0 Answers0