Assign NULL to List Element in R (2 Examples)

 

In this tutorial you’ll learn how to assign NULL to a list item in R.

The article contains the following topics:

Let’s get started:

 

Example Data

The first step is to create some example data.

my_list <- list(1:3,             # Create example list
                letters[1:5],
                "xxx",
                10:5)
my_list                          # Print example list
# [[1]]
# [1] 1 2 3
# 
# [[2]]
# [1] "a" "b" "c" "d" "e"
# 
# [[3]]
# [1] "xxx"
# 
# [[4]]
# [1] 10  9  8  7  6  5

The previous output of the RStudio console shows the structure of our example data: We have created a list object containing four different list elements.

 

Example 1: Drop List Element & Shift Others Using NULL

The R code below illustrates how to use NULL to delete a certain list element.

For this task, we have to use double square brackets to subset a certain list element, and then we have to assign NULL to this element:

my_list_new1 <- my_list          # Duplicate list
my_list_new1[[3]] <- NULL        # Remove list element
my_list_new1                     # Print new list
# [[1]]
# [1] 1 2 3
# 
# [[2]]
# [1] "a" "b" "c" "d" "e"
# 
# [[3]]
# [1] 10  9  8  7  6  5

As you can see based on the previous output, we have excluded the third list item from our list, and we have moved the fourth list element to the third position.

 

Example 2: Set List Element to NULL

In this example, I’ll demonstrate how to replace a particular list item by NULL.

To accomplish this, we have to use single square brackets, and we have to wrap the list() function around NULL:

my_list_new2 <- my_list          # Duplicate list
my_list_new2[3] <- list(NULL)    # Assign NULL to list element
my_list_new2                     # Print new list
# [[1]]
# [1] 1 2 3
# 
# [[2]]
# [1] "a" "b" "c" "d" "e"
# 
# [[3]]
# NULL
# 
# [[4]]
# [1] 10  9  8  7  6  5

This time, we have exchanged the third list element by NULL.

 

Video & Further Resources

I have recently released a video tutorial on my YouTube channel, which explains the R programming code of this page. You can find the video below.

 

The YouTube video will be added soon.

 

Furthermore, you may have a look at the other tutorials on my homepage.

 

In this tutorial you have learned how to assign NULL to a list element in the R programming language. Let me know in the comments, in case you have additional comments and/or questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top