remove first value from vector in R

R – Remove First Value From a Vector

Vectors are used to store one-dimensional data of the same type in R. In this tutorial, we will look at how to remove the first value from a vector in R with the help of some examples.

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

Negative indexing can be used to exclude values using their index from a vector. To remove the first value from a vector in R, you can use the negative index -1 inside the [] notation. The following is the syntax –

# remove first value from vector
vec <- vec[-1]

Note that using a negative index does not modify the vector in place. It simply filters the vector and returns a copy with the value at the given index removed. To modify the original vector, assign the resulting vector to the original vector variable.

You can similarly remove any value using its index from a vector in R.

Examples

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

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

# create a vector
vec <- c(10, 20, 30, 40)
# remove the first element
vec <- vec[-1]
# display the vector
print(vec)

Output:

[1] 20 30 40

Here, we use negative indexing to remove the value the index 1 (which is the first value in the vector). Note that we re-assign the returned vector to the variable vec. You can see that the first value from the original vector is not present in the resulting vector.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Let’s look at another example. This time let’s use a vector with named values.

# create a vector
vec <- c("a"=10, "b"=20, "c"=30, "d"=40)
# remove the first element
vec <- vec[-1]
# display the vector
print(vec)

Output:

 b  c  d 
20 30 40 

You can see that the first value from the original vector was removed.

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 Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top