[英]Question about recoding categorical variables in R
Very green R user here. 非常绿色的R用户。 I have to categorical variables: One is, committee crime against child or has mental health issues (dichotomous, 1= crime and 0 = mental health) and committed crime against child or has substance abuse issues (dichotomous, 1= crime and 0 = substance abuse). 我必须对类别变量进行分类:一种是,针对儿童的委员会犯罪或存在精神健康问题(两分,1 =犯罪,0 =精神健康),针对儿童的犯罪行为或存在滥用药物的问题(二分,1 =犯罪,0 =物质滥用)。 I'd like to combine these groups so I will have a dichotomous, crime against child and mental health or substance abuse group. 我想将这些群体合并在一起,这样我就会有一个二分法,危害儿童和心理健康或滥用毒品的群体。 What would be the best way to do this? 最好的方法是什么? I have been playing around with "if" statements but to no avail. 我一直在玩“ if”语句,但无济于事。
I have been playing around with "if" statements but to no avail. 我一直在玩“ if”语句,但无济于事。 I want to make a new variable in my dataset (com) that combines crime against child (1) and mental health/substance abuse (0) 我想在数据集(com)中创建一个新变量,该变量将针对儿童的犯罪(1)与心理健康/物质滥用(0)结合在一起
x$com <- if(x$Group.finalCvsM == 1) {
x$com("1") }
if(x$Group.finalCvsS == 1) {
x$com("1") }
if(x$Group.finalCvsM == 0) {
x$com("0") }
if(x$Group.finalCvsS == 0) {
x$com("0") }
Because your data is coded as binary 0/1, we can just use the logical OR operator, |
因为您的数据编码为二进制0/1,所以我们只能使用逻辑OR运算符|
. 。
## very nice way to solve this particular problem
x$com = x$Group.finalCvsM | x$Group.finalCvsS
## The result will be TRUE or FALSE.
## If you want 1/0 instead, then wrap it in as.integer:
x$com = as.integer(x$Group.finalCvsM | x$Group.finalCvsS)
In general , ifelse()
is a vectorized version of if
that is made for cases like this. 通常 , ifelse()
是if
的矢量化版本,适用于此类情况。 See the help page ?ifelse
for some detail. 请参阅帮助页面?ifelse
的一些细节。 Here you would use it as: 在这里,您可以将其用作:
x$com = ifelse(x$Group.finalCvsM == 1 | x$Group.finalCvsS == 1, 1, 0)
( Note:: since your question doesn't give sample input and desired output, I'm not 100% sure you want OR |
. Maybe you want &
? Both work fine, use whichever meets your goal.) ( 注意:由于您的问题没有给出示例输入和所需的输出,因此我不确定100%是否需要OR |
。也许您希望&
?都可以正常工作,请使用满足您目标的方法。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.