How do I create a new column in r that is a binomial variable based on a string variable? [duplicate]

泪湿孤枕 提交于 2021-02-05 12:21:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!