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:
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 2 3 # # [] #  "a" "b" "c" "d" "e" # # [] #  "xxx" # # [] #  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[] <- NULL # Remove list element my_list_new1 # Print new list # [] #  1 2 3 # # [] #  "a" "b" "c" "d" "e" # # [] #  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 <- list(NULL) # Assign NULL to list element my_list_new2 # Print new list # [] #  1 2 3 # # [] #  "a" "b" "c" "d" "e" # # [] # NULL # # [] #  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.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may have a look at the other tutorials on my homepage.
- List Error in R – attempt to select less than one element in get1index real
- Select Random Element from List
- Index Element of List in R
- Test If List Element Exists in R
- All R Programming Examples
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.
Statistics Globe Newsletter