Remove Multiple Values from Vector in R (Example)
On this page, I’ll show how to delete certain values from a vector in the R programming language.
The content of the page looks as follows:
Here’s how to do it!
Creating Example Data
First, we need to create an example vector in R:
vec <- c("A", "B", "A", "C", "D") # Create example vector vec # Print example vector # "A" "B" "A" "C" "D"
Our example vector consists of five character elements. Now, let’s remove some of these elements…
Example: Delete Certain Values from Vector
If we want to remove multiple values from a vector, we can use the %in% operator. Have a look at the following R code:
vec_new <- vec[! vec %in% c("A", "C")] # Remove multiple values vec_new # Print updated vector # "B" "D"
As you can see based on the output of the RStudio console, we deleted every “A” and every “C” from our vector.
Video, Further Resources & Summary
Would you like to know more about removing certain values from vectors and data frame columns? Then you may have a look at the following video of my YouTube channel. I’m explaining the R programming codes of this tutorial in the video.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you might read the other articles that I have published on my homepage.
In this R tutorial you learned how to extract specific entries from a vector or data frame variable. Please let me know in the comments section, if you have further questions. Furthermore, please subscribe to my email newsletter in order to receive updates on the newest tutorials.
Statistics Globe Newsletter
4 Comments. Leave new
J’ai une base de données sur R ou j’ai des valeurs aberrantes , cad 99 et 0 d’une variables AGE.Je souhaite les supprimer
besoin d’aide
Hey Younoussa,
You can cut off your variable using the following R code:
Regards, Joachim
What if you want to return the deleted values to the vector? I’m trying to return the 100th and 200th elements to a vector of even only numbers 1:1000
Hey Alice,
You may extract these values using the following code: vec[c(100, 200)].
Regards,
Joachim