NULL Object in R

NULL represents the null object in R. It represents an object that has no value.

Example 1: Creating a NULL

To create a NULL, assign it to a variable.

Diagram of NULL in R
Figure 1: Creating a NULL in R
vec <- NULL

vec

typeof(vec)

Output

NULL
[1] "NULL"

Example 2: Using NULL as a placeholder

main_function <- function() {
  return(NULL)
}

# call the function and assign the result to a variable
null_res <- main_function()

# print the result
print(null_res)

Output

NULL

Example 3: Length of NULL

The length of NULL is always zero.

length(NULL)

Output

[1] 0

Example 4: is.null() function

The is.null() function checks whether the data object is NULL. It returns the logical vector, either TRUE or FALSE.

Syntax

is.null(x)

Parameters

x: It is an R object to be tested.

Visual Representation

Visual Representation of is.null() function
Figure 2: How is.null() function works

Example

rv <- NULL
rv
is.null(rv)

Output

NULL
[1] TRUE

Example 5: as.null() function

You can use the as.null() function to convert a variable to NULL, which ignores its argument and returns the value NULL.

Syntax

as.null(x)

Parameters

x: It is an object to be tested or coerced.

Visual Representation

Using the as.null() function in R
Figure 3: Usage of as.null() function

Example

vec <- c(1, 2, 3, 4, 5)
vec

cat("Converting a vector to NULL", "\n")

vec_null <- as.null(vec)
vec_null
is.null(vec_null)

Output

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

NULL vs. NA and NaN

  1. NULL denotes the absence of a value or an undefined state.
  2. NA represents a missing value in a vector or data set.
  3. NaN stands for “Not a Number” and typically results from undefined mathematical operations.

Leave a Comment