'How to match at least two conditions in r

I have a dataframe:

df1<-data.frame(A=rnorm(100,mean = 10,sd=1),B=rnorm(100,mean = 10,sd=1))

and 4 conditions:

cond1<-df1$A+1>df1$B
cond2<-df1$A+2>df1$B
cond3<-df1$A+3>df1$B
cond4<-df1$A+4>df1$B

If I want to match any of the condition and turn Ato 0, I will do:

df1[cond1|cond2|cond3|cond4,"A"]<-0

What if I want to match at least two or at least three of the conditions? Is there a easy way?

r


Solution 1:[1]

Here is one way using sums.

At least two:

df1[(cond1+cond2+cond3)>=2,"A"]=0

Less than two:

df1[(cond1+cond2+cond3)<2,"A"]=0

Cond1 and at least one of cond2 or cond3:

df1[cond1+(cond2+cond3)>=1,"A"]=0

Etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1