There are the following methods to remove an element from a list in R.
Method 1: Remove an element from a list using a minus sign
The easiest way to remove an element from a list in R is to use a minus sign (-) or negative indexing. For example, you can remove the second element from the main_list using the main_list[–2] expression.
Example
main_list <- list("bmw", "audi", "benley", "mercedez")
main_list <- main_list[-3]
print(main_list)
Output
[[1]]
[1] "bmw"
[[2]]
[1] "audi"
[[3]]
[1] "mercedez"
You can see that we removed the third element from the list using negative indexing.
Method 2: Remove Element from List using NULL
You can set the element at a specific position to NULL to remove it from the list in R.
Example
[[1]]
[1] "bmw"
[[2]]
[1] "audi"
[[3]]
[1] "mercedez"
Output
[[1]]
[1] "bmw"
[[2]]
[1] "audi"
[[3]]
[1] "mercedez"
Method 3: Remove list element by Name with %in% Operator
The “%in%” operator returns a logical vector, which suggests whether a certain value of a data object exists in another element.
Example
main_list <- list(a = "bmw", b = "audi", c = "benley", d = "mercedez")
updated_list <- main_list[names(main_list) %in% "c" == FALSE]
updated_list
Output
$a
[1] "bmw"
$b
[1] "audi"
$d
[1] "mercedez"
Method 4: Using Filter and != operator
If you want to remove an element based on its value, you can use the filter() function.
Example
main_list <- list("bmw", "audi", "bentley", "mercedez")
main_list <- Filter(function(x) x != "bentley", main_list)
print(main_list)
Output
[[1]]
[1] "bmw"
[[2]]
[1] "audi"
[[3]]
[1] "mercedez"
Remember that this method will remove all occurrences of the specified value in the list.
Remove Multiple Elements from a List
You can remove multiple elements from a list in R by passing the vector containing the indices of the vector values.
Example
main_list <- list(a = "bmw", b = "audi", c = "benley", d = "mercedez")
updated_list <- main_list[-c(1, 3)]
updated_list
Output
$b
[1] "audi"
$d
[1] "mercedez"
You can also assign NULL to the indices vector to remove the list elements.
main_list <- list(a = "bmw", b = "audi", c = "benley", d = "mercedez")
updated_list <- main_list
updated_list[c(1, 3)] <- NULL
updated_list
Output
$b
[1] "audi"
$d
[1] "mercedez"
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.