mercredi 18 septembre 2019

Multiple OR conditions for a range of columns in ifelse R

Using R, I have a dataframe:

ID col1 col2 col3 ... col20
1   0     0    2        0
2   3     1    0        0
3   0     0    0        1

I want to have a column called cond in which if any of the columns from col1 to col3 have a value >=2, it is 1, otherwise 0. So instead of writing multiple OR conditions I tried writing with a single line of code:

df$cond <- ifelse (df[2:4] >= 2, 1, 0)

This returns all the values of the cond = 0.

I will be glad to hear about your solutions.

Aucun commentaire:

Enregistrer un commentaire