问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/49504282/how-do-i-create-a-new-column-in-r-that-is-a-binomial-variable-based-on-a-string