Generating a new binomial variable from existing variables

时光怂恿深爱的人放手 提交于 2020-01-05 04:28:06

问题


Suppose I have the following data:

Var1 = (1,1,0,1,0,1,0,1,1,0,1,1,0,0,0,1,0)
Var2 = (1,0,0,1,1,0,0,1,0,1,0,1,1,1,0,1,1)
Var3 = (0,0,0,1,1,1,0,0,1,0,1,0,0,0,1,0,0)

Using if/else syntax in R, I need to create new Var4, so that

if var1=1 & var2=1 & var3=1 then var4=1
if var1=0 & var2=0 & var3=0 then var4=0
if var1=1 & var2=0 & var3=0 the var4=1 and so on.

Basically, var4=0 when all three variables=0 only.


回答1:


We can cbind the 'var' vectors, get the rowSums and check if it is greater than 0, coerce the logical to binary with +

+(rowSums(cbind(Var1, Var2, Var3)) > 0)

Or use |

as.integer(Var1|Var2|Var3)


来源:https://stackoverflow.com/questions/58895792/generating-a-new-binomial-variable-from-existing-variables

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