Convert values of an Object to Logical Vector in R Programming – as.logical() Function

as.logical() Function in details

The as.logical() function in R is used to convert an object to a logical vector.

Syntax:

as.logical(x)

Parameters:

  • x: Numeric or character object.

Example 1: Basic Example of as.logical() Function in R

# R Program to convert an object to a logical vector

# Creating a vector
x <- c(0, 1, 2, -3, 4, NA)

# Calling as.logical() function
print(as.logical(1))
print(as.logical("FALSE"))
print(as.logical(0))
print(as.logical(x))

Output:

[1] TRUE
[1] FALSE
[1] FALSE
[1] FALSE  TRUE  TRUE  TRUE  TRUE    NA

Example 2: Converting Matrices with as.logical() Function in R

# R Program to convert matrices to logical vectors

# Creating matrices
matrix1 <- matrix(c(0, 1, 3, 4), 2, 2)
matrix2 <- matrix(c(0, 0, 1, -1), 2, 2)

# Calling as.logical() function
print(as.logical(matrix1))
print(as.logical(matrix2))

Output:

[1] FALSE  TRUE  TRUE  TRUE
[1] FALSE FALSE  TRUE  TRUE

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *