R Logical Vectors

R Logical Vector is an atomic vector whose type is “logical”. A logical value is either TRUE or FALSE. Logical vector items can have a value of NA as well.

In this tutorial, we will learn how to create a logical vector in R, with examples.

Allowed Values in Logical Vector

The following are the list of values allowed in a logical vector.

  • TRUE
  • FALSE
  • NA
ADVERTISEMENT

Create a Logical Vector using c()

To create a logical vector, we can use c() function.

In the following example, we create a logical vector with length 5. We print the type of vector, and the vector contents.

example.R

x <- c(TRUE, FALSE, FALSE, NA, TRUE, NA)
print(typeof(x))
print(x)

Output

1] "logical"
[1]  TRUE FALSE FALSE    NA  TRUE    NA

Create Logical Vector from Comparisons

We can also create a logical vector from comparisons.

For example, we take a numeric vector, and check if the items are even.

In the following program, x is a numeric vector, and we check if its values are even using Equal-to == comparison operator.

example.R

x <- c(2, 3, 7, 6, 1)
result <- x%%2 == 0
print(result)

Output

[1]  TRUE FALSE FALSE  TRUE FALSE

Conclusion

In this R Tutorial, we learned what logical vectors are, different values allowed in a logical vector, and how to create a logical vector, with the help of examples.