mercredi 17 février 2021

Using ifelse conditional on multiple columns

I want to generate variables to check whether a specific event occurred over multiple conditions. A sample dataframe is below.

df <- data.frame(
    index = c(1:20),
    con1 = c(1,3,2,4,2,7,5,9,1,2,5,6,1,0,8,0,4,5,7,3),
    con2 = c(3,5,1,6,3,4,7,3,2,1,5,7,9,1,4,2,4,3,4,3),
    con3 = c(2,7,3,4,1,9,4,0,7,0,5,2,7,5,9,3,5,2,1,2))

The actual dataset has 20 conditions[con*] and 10 different event types (each number in the [con*].

What I am doing now is using a tedious command like this;

df %>% mutate (Event1 = ifelse (con1==1 | con2==1 | con3==1,1,0))
df %>% mutate (Event2 = ifelse (con1==2 | con2==2 | con3==2,1,0))
...

It gives exactly what I want to get. However, you can imagine how much mess this makes in the script, with 20 conditions and 10 different events. Do you have any idea how can I make it neat?

Aucun commentaire:

Enregistrer un commentaire