is.list() Function: Check If an Object is List in R

The is.list() function in R checks if an input object is a list. It returns TRUE if an object is a list and FALSE otherwise. This function checks if an object itself is a list, not the elements of the list. 

For example, if a list has vector and data frames, it is still a list. It does not matter the type of elements of the list.

Some functions require input to be a list, and we can use this function to ensure that what we are passing is a list. This function helps us confirm that we are, in fact, dealing with lists and ensures an error-free process.

Syntax

is.list(obj)

Parameters

Name Value
obj It is an input object that you want to check for a list.

Checking list

Checking list type

main_list <- list(1, "kb", 3.14, c(1, 2, 3))

is.list(main_list) # [1] TRUE

We created a list of different types, printed it, and check if it is a list object. As expected, the output is TRUE.

Checking list elements

Checking list elements

If you check for specific elements of the list, that element must be a list to get the output TRUE; otherwise, it is FALSE.

main_list <- list(1, "kb", 3.14, c(1, 2, 3))

is.list(main_list[[4]]) # [1] FALSE

Since the fourth element of the list is a vector, we get the output FALSE.

Checking non-list type

vec <- c(11, 21)

is.list(vec) # [1] FALSE

As expected, if you pass anything other than the list, it returns FALSE.

Proper application

One proper application of this function is to use with if statement and create a condition where an object must be a list, and if it is not, then show something meaningful to the user.

main_list <- list(1, "kb", 3.14, c(1, 2, 3))

# Use if statement with is.list
if (is.list(main_list)) {
  print("main_list is a list")
} else {
  print("main_list is not a list")
}

# Output: [1] "main_list is a list"

is.list() vs typeof()

The main difference between is.list() and typeof() functions is that is.list() function checks if an object is of the class list, whereas the typeof() function checks the internal storage mode of the object.

main_list <- list(1, "kb", 3.14, c(1, 2, 3))

is.list(main_list) # [1] TRUE

typeof(main_list) # [1] "list"

That’s all!

Leave a Comment