如何在r中创建新列,该列是基于字符串变量的二项式变量? [英] How do I create a new column in r that is a binomial variable based on a string variable?

查看:40
本文介绍了如何在r中创建新列,该列是基于字符串变量的二项式变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用mutate()在另一列的基础上在数据框中创建新列.

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

我要基于新列是否表示活动",将新列设为二项式变量(1或0).我目前正在尝试通过说:

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 }

这当前会产生警告消息:在if(violations $ RESULT ==活跃的老鼠迹象"){:条件的长度> 1,并且只会使用第一个元素",然后查看新数据框,每个 violations $ outcome 均为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.

推荐答案

R有一个方便的函数,称为 ifelse

R has a handy function called ifelse

尝试 violations $ outcome = ifelse(violations $ RESULT =='Active',1,0).第一个参数是要测试的条件,第二个参数是 TRUE 时返回的内容,第三个参数是 FALSE 时返回的内容.

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.

这篇关于如何在r中创建新列,该列是基于字符串变量的二项式变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆