R Basic

is.logical() Function: Check If a Value is Logical in R

R is.logical() function checks whether an input object’s data type is logical. If the object is logical whose values are either TRUE or FALSE, it returns TRUE; otherwise, it is FALSE.

This function checks the underlying type of the object.

Due to the nature of the function, you can use it in conditional statements to validate user input.

Syntax

is.logical(obj)

Parameters

Name Value
obj It is an object that needs to be checked for a logical type.

Testing basic values

logical_val_one <- TRUE
logical_val_two <- FALSE

is.logical(logical_val_one) # TRUE
is.logical(logical_val_two) # TRUE

You can see that TRUE and FALSE are logical values and return TRUE.

Let’s pass non-logical values and see the output:

is.logical(0) # FALSE

is.logical("hello") # FALSE

0 is the logical gate, but in R, it is a numeric value, so it returns FALSE.

Testing a Vector

If you create a vector that contains TRUE or FALSE values, this function returns TRUE.

vec_logical <- c(TRUE, FALSE, TRUE, FALSE)

is.logical(vec_logical) # TRUE

If you pass a non-logical vector, it returns FALSE.

non_logical_vec <- c(1, 2, 3, 4)

is.logical(non_logical_vec) # FALSE

Testing a List

The lists are not logical objects, so even if you pass all the elements of the list as logical values, it still returns FALSE.

list_obj <- list(TRUE, FALSE)

is.logical(list_obj) # FALSE

Testing NA (Not Available)

NA represents missing value, and missing value can be anything, including logical type. So, if you pass NA to the is.logical() function, it returns TRUE.

is.logical(NA) # TRUE

Testing NaN (Not A Number)

NaN represents undefined numerical results, which means they are not logical values by default and cannot become one. So, it returns FALSE.

is.logical(NaN) # FALSE

Testing NULL

NULL represents an empty object, which means there is nothing, including logical values. Hence, it returns FALSE.

is.logical(NULL) # FALSE

That’s all!

Recent Posts

cbind() Function: Binding R Objects by Columns

R cbind (column bind) is a function that combines specified vectors, matrices, or data frames…

5 days ago

rbind() Function: Binding Rows in R

The rbind() function combines R objects, such as vectors, matrices, or data frames, by rows.…

5 days ago

as.numeric(): Converting to Numeric Values in R

The as.numeric() function in R converts valid non-numeric data into numeric data. What do I…

2 weeks ago

Calculating Natural Log using log() Function in R

The log() function calculates the natural logarithm (base e) of a numeric vector. By default,…

3 weeks ago

Dollar Sign ($ Operator) in R

In R, you can use the dollar sign ($ operator)  to access elements (columns) of…

1 month ago

Calculating Absolute Value using abs() Function in R

The abs() function calculates the absolute value of a numeric input, returning a non-negative (only…

1 month ago