0

We have vectors as follows:

c1<-c(10,40,28)
c2<-c(50,55,44)

this code:

c1>25&&c2>25

returns FALSE which I understand (&& return always one, scalar value, if it encounters FALSE values it doesn't make any sesne to check the rest values in vectors)

However in this example:

c3<-c(40,10,28)
c4<-c(50,15,44)

for this code:

c3>25&&c4>25

it returns TRUE. I don't understand why. I read that for && and || only first elements are being checked but for me it doesn't make sense. values 40 and 50 (those first elements) return TRUE but pair: 10 and 15 returns FALSE and for me teh output should be FALSE beacuse rest ofe the vector values (besides first elenents) are not TRUE and the whole output should be FALSE. That's misleading.

When I compare 2 vectors such as above - I would like to return FALSE not TRUE because they don't meet the condition (>25). How can I compare them to return FALSE instead of TRUE )(for me && is useless in this case)

Muska
  • 283
  • 4
  • 15

2 Answers2

2

As you have already learned x && y only checks the first element of x and y

c(TRUE, FALSE) && c(TRUE, FALSE)

Evaluates to TRUE since the only thing that is tested is TRUE && TRUE

On the other hand:

c(TRUE, TRUE) & c(TRUE, FALSE)

Evaluates to c(TRUE, FALSE) since & tests all pairings.

If you want to know if all parings are TRUE we can use:

all(c(TRUE, TRUE) & c(TRUE, FALSE))

Which at first evaluates to:

all(c(TRUE, FALSE))

And then to:

FALSE
dario
  • 6,415
  • 2
  • 12
  • 26
1

If you read ?Logic it is clearly mentioned that :

& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined.

&& checks only for first value in c3 and c4 and since that is TRUE it returns the output as TRUE.

What you probably need for your use case is :

all(c3 > 25 & c4 > 25)
#[1] FALSE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213