问题
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