Delete List Element in R (Example)
The following R code shows how to remove elements from a list in the R programming language.
Example Data
my_list <- list(letters[1:5], c(1, 5, 7), 1:10, "X") names(my_list) <- LETTERS[1:4] my_list # $A # [1] "a" "b" "c" "d" "e" # # $B # [1] 1 5 7 # # $C # [1] 1 2 3 4 5 6 7 8 9 10 # # $D # [1] "X" |
my_list <- list(letters[1:5], c(1, 5, 7), 1:10, "X") names(my_list) <- LETTERS[1:4] my_list # $A # [1] "a" "b" "c" "d" "e" # # $B # [1] 1 5 7 # # $C # [1] 1 2 3 4 5 6 7 8 9 10 # # $D # [1] "X"
Remove Element from List in R
If we want to delete certain list elements in R, we can use the %in% operator to subset our list as follows:
my_list_updated <- my_list[names(my_list) %in% c("B", "D") == FALSE] my_list_updated # $A # [1] "a" "b" "c" "d" "e" # # $C # [1] 1 2 3 4 5 6 7 8 9 10 |
my_list_updated <- my_list[names(my_list) %in% c("B", "D") == FALSE] my_list_updated # $A # [1] "a" "b" "c" "d" "e" # # $C # [1] 1 2 3 4 5 6 7 8 9 10