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.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

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.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top