# Errors generated when attempting to use Logical Operators (&&, ||)

Hello,

I am learning R as part of the overall curriculum for the Google Data Analysis certificate. I am currently on Lesson 7, Week 3 "More on R operators".

The lesson explains the following

Logical AND (&&) and OR (||)

The main difference between element-wise logical operators (&, |) and logical operators (&&, ||) is the way they apply to operations with vectors. The operations with double signs, AND (&&) and logical OR (||), only examine the first element of each vector. The operations with single signs, AND (&) and OR (|), examine all the elements of each vector.

For example, imagine you are working with two vectors that each contain three elements: c(3, 5, 7) and c(2, 4, 6). The element-wise logical AND (&) will compare the first element of the first vector with the first element of the second vector (3&2), the second element with the second element (5&4), and the third element with the third element (7&6).

Now check out this example in R code.

First, create two variables, x and y, to store the two vectors:

x <- c(3, 5, 7)

y <- c(2, 4, 6)

Then run the code with a single ampersand (&). The output is boolean (TRUE or FALSE).

x < 5 & y < 5

[1] TRUE FALSE FALSE

When you compare each element of the two vectors, the output is TRUE, FALSE, FALSE. The first element of both x (3) and y (2) is less than 5, so this is TRUE. The second element of x is not less than 5 (itâ€™s equal to 5) but the second element of y is less than 5, so this is FALSE (because you used AND). The third element of both x and y is not less than 5, so this is also FALSE.

Now, run the same operation using the double ampersand (&&):

x < 5 && y < 5

[1] TRUE

In this case, R only compares the first elements of each vector: 3 and 2. So, the output is TRUE because 3 and 2 are both less than 5.

I was successfull in reproducing the output of x < 5 & y < 5. However, when I attempted to run x < 5 && y < 5, I get the following error:

Error in x < 5 && y < 5 : 'length = 3' in coercion to 'logical(1)'

I attempted to try x < 5 || y < 5 as well, but unfortunately received another error:

Error in x < 5 || y < 5 : 'length = 3' in coercion to 'logical(1)'

Is anyone able to explain why these errors are being triggered despite following exactly what the course detailed I should do?

Hi Paul,
Welcome to the community! The error you're seeing is due to the recent changes in R 4.3.0 R 4.3.0 NEWS which will now throw an error with && and || instead of simply evaluating the first element if the length of the vectors being compared > 1.

@jrmuirhead Thank you for informing me about this change.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.