Karan
Karan

Reputation: 125

logical operators and, or are not working

The R condition is not working properly.

I am using logical operators && and || but both are not working.

df = data.frame(c("enrty 1","enrty 2","enrty 3") ,c(12200, 1, 120), c(111111, 12, 123), c(1, 1, 0 ) , c(0,1,0), c(1,0,1))

names(df) = c('Name', 'X1', 'X2', 'X3','X4','X5')

if (((df$X3 > 1) || (df$X1  < 1000)) &&  ((df$X4 > 1) || (df$X2 < 1000))){
  df$condition1 = 1
} else {
  df$condition1 = 0
}

if ((df$X3 > 1) || (df$X1  < 1000)) {  
  df$condition2 = 1
} else {
  df$condition2 = 0
}

if ((df$X4 > 1) || (df$X2 < 1000)) {  
  df$condition3 = 1
} else {
  df$condition3 = 0
}

Output: https://drive.google.com/file/d/1P6VrT-xePBXNaYUi2fdKTJyuhThc4jcf/view?usp=sharing

Upvotes: 0

Views: 1097

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388907

A straight-forward way to do what you need would be to use a vectorized approach

df$condition <- +(with(df, (X3 > 1 | X1  < 1000) &  (X4 > 1 | X2 < 1000)))

df
#     Name    X1     X2 X3 X4 X5 condition
#1 enrty 1 12200 111111  1  0  1         0
#2 enrty 2     1     12  1  1  0         1
#3 enrty 3   120    123  0  0  1         1

The + in the beginning converts logical values to integers.

Also read : Boolean operators && and ||

Upvotes: 1

Related Questions