Skip to Content

Remove First Value From a List in R

In this tutorial, we will look at how to remove the first value from a list in R with the help of some examples.

How to remove the first value in a List in R?

You can remove the first value from a list in R by setting the value at the first index in the list to NULL. The following is the syntax –

# remove first value from list
ls[1] <- NULL

You can also use the above syntax to remove any value from a list using its index. Just replace 1 with the index of the value you want to remove from the list.

Examples

Let’s look at some examples of removing the first value from a list in R.

First, let’s create a list with four values and remove the first value using the syntax mentioned above.

# create a list
ls <- list("a", "b", "c", "d")
# remove the first element
ls[1] <- NULL
# display the list
print(ls)

Output:

[[1]]
[1] "b"

[[2]]
[1] "c"

[[3]]
[1] "d"

Here, we create a list of four character values and then set the value at the first index in the list to NULL. We then print the list. You can see that the list now does not have the first value from the original list.

Alternatively, you can use negative indexing to exclude values at certain indexes (for our use case, remove the first value). Note that this does not modify the list in place. To modify the original list, assign the result from the negative indexing to the original list variable.

Let’s remove the first element from the same list used in the example above. A list of four character values.

# create a list
ls <- list("a", "b", "c", "d")
# remove the first element
ls <- ls[-1]
# display the list
print(ls)

Output:

[[1]]
[1] "b"

[[2]]
[1] "c"

[[3]]
[1] "d"

You can see that we get the same result as above.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.