-1

I'm currently trying to create a new column in my data frame based on another column using mutate().

I want to make the new column a binomial variable (1 or 0) based on whether the column its based on says "Active" or not. I'm currently trying to do it by saying:

violations$outcome = if (violations$RESULT == "Active") { 1 } else { 0 }

This currently produces the "Warning message: In if (violations$RESULT == "Active Rat Signs") { : the condition has length > 1 and only the first element will be used" and I look at my new data frame and every violations$outcome is 0.

Does anyone have any idea how to do this and why my original answer isn't working? This is very frustrating and I would appreciate any comments, advice, or help you have to offer. Thank you.

namore
  • 83
  • 2
  • 9
  • 1
    `ifelse` is the vectorize `if`, so `violations$outcome = ifelse(violations$RESULT == "Active", 1, 0)`. But you can coerce a logical to numeric, so most people prefer `violations$outcome = as.integer(violations$RESULT == "Active")` because it's more efficient. – Gregor Thomas Mar 27 '18 at 04:24

1 Answers1

2

R has a handy function called ifelse

Try violations$outcome = ifelse(violations$RESULT == 'Active', 1, 0). The first argument is the condition you're testing, the second argument is what to return if it is TRUE and the third agrument is what to return if it's FALSE.

Keith Mertan
  • 136
  • 4
  • Awesome! I also found out I could do 'violations = mutate(violations, ratsigns = ifelse(RESULT == "Active Rat Signs", 1, 0))' using dplyr – namore Mar 27 '18 at 04:28