How to remove an Element from a List in R

04.06.2021

R doesn't provide us with a built in delete or remove function, but removing items from a list is pretty simple. We can also use multiple indexing to remove multiple elemets. In this article, we will see how to remove an element from a list in R.

The first way we can remove items from a list is with the position index. To remove elements, we set the value to NULL

lst = list(1, 2, 3)

lst[[1]] = NULL # remove the first element

We can also remove multiple elements with a vector of positions.

lst = list(1, 2, 3)

lst[c(1, 3)] = NULL # removes the first and third element

Next, we can also remove lists using the names or keys of the values and setting the values to null.

group = list(count = 3, name = "test", details = c(1, 2, 3))

group[["count"]] = NULL

Again, we can also remove multiple elements using a vector and setting all values to NULL.

group = list(count = 3, name = "test", details = c(1, 2, 3))

group[c("count", "details")] = NULL