Beata
Beata

Reputation: 7

How to create new variable from two existing categorical variables

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

Answers (2)

tmfmnk
tmfmnk

Reputation: 39858

For this, you can also use:

pmax(Var1, Var2)

[1] 1 1 1 1 0

Upvotes: 1

akrun
akrun

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))

data

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

Related Questions