How to Assign NULL to a List Item in R (2 Examples)
In this tutorial you’ll learn how to assign NULL to a list element in R.
Creation of Example Data
x <- list(10:4, # Constructing an example list LETTERS[8:5], c(4, 1, 5, 2, 6, 3), "abcde", 10:15) x # [[1]] # [1] 10 9 8 7 6 5 4 # # [[2]] # [1] "H" "G" "F" "E" # # [[3]] # [1] 4 1 5 2 6 3 # # [[4]] # [1] "abcde" # # [[5]] # [1] 10 11 12 13 14 15 |
x <- list(10:4, # Constructing an example list LETTERS[8:5], c(4, 1, 5, 2, 6, 3), "abcde", 10:15) x # [[1]] # [1] 10 9 8 7 6 5 4 # # [[2]] # [1] "H" "G" "F" "E" # # [[3]] # [1] 4 1 5 2 6 3 # # [[4]] # [1] "abcde" # # [[5]] # [1] 10 11 12 13 14 15
Example 1: Removing a List Element by Assigning NULL
x_updated1 <- x # Delete list element x_updated1[[4]] <- NULL x_updated1 # [[1]] # [1] 10 9 8 7 6 5 4 # # [[2]] # [1] "H" "G" "F" "E" # # [[3]] # [1] 4 1 5 2 6 3 # # [[4]] # [1] 10 11 12 13 14 15 |
x_updated1 <- x # Delete list element x_updated1[[4]] <- NULL x_updated1 # [[1]] # [1] 10 9 8 7 6 5 4 # # [[2]] # [1] "H" "G" "F" "E" # # [[3]] # [1] 4 1 5 2 6 3 # # [[4]] # [1] 10 11 12 13 14 15
Example 2: Setting a List Element to NULL
x_updated2 <- x # Replace list element by NULL x_updated2[4] <- list(NULL) x_updated2 # [[1]] # [1] 10 9 8 7 6 5 4 # # [[2]] # [1] "H" "G" "F" "E" # # [[3]] # [1] 4 1 5 2 6 3 # # [[4]] # NULL # # [[5]] # [1] 10 11 12 13 14 15 |
x_updated2 <- x # Replace list element by NULL x_updated2[4] <- list(NULL) x_updated2 # [[1]] # [1] 10 9 8 7 6 5 4 # # [[2]] # [1] "H" "G" "F" "E" # # [[3]] # [1] 4 1 5 2 6 3 # # [[4]] # NULL # # [[5]] # [1] 10 11 12 13 14 15
Related Articles
You may find some related R programming tutorials in the following list: