NULL in R: What is NULL Object in R Programming

In computer programmingnull or NULL is both a value and a pointer. Null is a constant in the programming languages with zero or close to zero like nothing. If a reference points to null, it simply means that there is no value associated with it. So let’s cut the chase and coming to R Programming.

To convert any R Object to NULL, assign the NULL value to that Object or use the as.null() function and pass the Object to that function, and it will return NULL.

NULL in R

The NULL represents the NULL object in R. NULL is used largely to represent the lists with zero length and is usually returned by expressions and functions whose value is undefined.

To define a NULL, assign it to a variable, and that variable becomes NULL.

rv <- NULL
rv
typeof(rv)

Output

NULL
[1] "NULL"

To create a NULL variable, assign the value NULL to any variable, and that variable has a NULL value.

R provides two functions to deal with NULL.

  1. is.null()
  2. as.null()

is.null() function in R

The is.null() is an inbuilt R function that checks if the variable has a NULL value or not. It returns the logical vector, either TRUE or FALSE.

rv <- NULL
rv
is.null(rv)

Output

NULL
[1] TRUE

Let’s define a list of mix values, including NULL value, and use the is.null() function to see the output.

rl <- list(1, 2, NULL, 4, 5)
rl
cat("Checking the NULL value", "\n")
is.null(rl)

Output

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
NULL

[[4]]
[1] 4

[[5]]
[1] 5

Checking the NULL value
[1] FALSE

You can see from the output that it is.null() function returns FALSE.

Let’s check the same for the vector in R to see if we get the same output.

rv <- c(1, NULL, 2, 4, 3)
rv
cat("Checking the NULL value of Vector", "\n")
is.null(rv)

Output

[1] 1 2 4 3
Checking the NULL value of Vector
[1] FALSE

And we get the FALSE in the output but let’s fill all the values with NULL and use the is.null() function again!

rv <- c(NULL, NULL, NULL, NULL, NULL)
rv
cat("Checking the NULL value of Vector", "\n")
is.null(rv)

Output

NULL
Checking the NULL value of Vector
[1] TRUE

Surprise! It returns TRUE that means if all the vector elements are NULL, then is.null() returns TRUE.

as.null() function in R

The as.null() function ignores its argument and returns the value NULL.

Syntax

as.null(x, ...)

Parameters

The x is an object to be tested or coerced.
The … will be ignored.

Example

rv <- c(1, 2, 3, 4, 5)
rv
cat("Converting a vector to NULL", "\n")
rv_null <- as.null(rv)
rv_null
is.null(rv_null)

Output

[1] 1 2 3 4 5
Converting a vector to NULL
NULL
[1] TRUE

As we can see that the as.null() function converts R Vector to NULL. This way, you can create any data type to NULL by just assigning the value NULL or use the as.null() function to convert it to NULL.

That is it for a NULL value in the R language.

See also

NaN in R

NA in R

Leave a Comment