从r中的序数数据中创建虚拟变量
我有一个序数变量,以下类别
非常有利(1) 有点有利(2) 有点不利(3) 非常不利(4) 不知道(8) 拒绝回答(9)
我想要我的输出二进制可显示的变量:
有利(1) 不利(0)
我想通过将“非常有利的”和“有利”组合在一起,以编码为“ 1”的新“有利”结果 还将“非常不利”和“有点有利”组合在一起,对新结果“不利”编码为“ 0”。
,我基本上想将“ 1” =“ 1”和“ 2” =“ 1” then,然后3“ =“ 0”和“ 4” =“ 0”
I have an ordinal variable with the following categories
very favorable (1)
somewhat favorable (2)
somewhat unfavorable (3)
very unfavorable (4)
don't know (8)
refuse to answer (9)
I want my output binary variable to display:
favorable (1)
unfavorable (0)
I want to do that by grouping together "very favorable" and "somewhat favorable" to the new "favorable" outcome coded in "1"
and also group together "very unfavorable" and "somewhat favorable" to new outcome "unfavorable coded as "0".
So basically I want to turn "1" = "1" and "2" = "1" then "3" = "0" and "4" = "0"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是
dplyr
带有case_when()
的解决方案,对于创建假人确实很有用。我的启动数据如下:
因此,基本上,当它检测到1或2时,它会将行值转换为“有利(1)”,而3或4则将“不利(0)”转换
为(8)和(9) s未指定,代码将其返回为NAS。
最终数据集如下:
Here's a
dplyr
solution withcase_when()
which is really useful for creating dummies.My starting data is as follows:
So, basically, when it detects 1 or 2, it will convert the row value into "favorable (1)" and 3 or 4 into "unfavorable (0)"
Since (8) and (9) s not specified, the code returns them as NAs.
Final dataset is as follows:
我能想到的最简单的方法是多种方法是利用百分比的百分比。
例如,在基本r中:
那么,如果您真的想要奖金点,则可以将其重新归因于一个因素变量,但我发现这通常过于过多。
我无法从您的原始问题中分辨出数字代码是否正常,或者您是否想使用字符字符串,但是适用相同的逻辑,例如:
应该为您提供所需的东西。
Lots of ways to do this, easiest way I can think of is making use of some %in%.
e.g, in base R:
Then if you really want bonus points you could coerce this back into a factor variable, but I find this is usually excessive.
I couldn't tell from your original question if the numeric codes were fine or if you wanted to use character strings instead, but the same logic applies, e.g:
should get you what you need.