Reputation: 7
I need to generate a new variable from two existing dichotomous variables. Example:
Var1 = c(1,0,1,0,0)
Var2= c(0,1,1,1,0)
and new variable should look like:
Var3= c(1,1,1,1,0)
Basically, when var1=1
and var2=0
then var3=1
; and so on.
Upvotes: 0
Views: 112
Reputation: 887118
We can use |
df1$Var3 <- with(df1, +(Var1|Var2))
df1$Var3
#[1] 1 1 1 1 0
Or sum and then create logical
df1$Var3 <- with(df1, as.integer((Var1 + Var2) > 0))
df1 <- structure(list(Var1 = c(1L, 0L, 1L, 0L, 0L), Var2 = c(0L, 1L,
1L, 1L, 0L)), row.names = c(NA, -5L), class = "data.frame")
Upvotes: 2