13.2 C
London
Tuesday, July 2, 2024
HomeStatistics TutorialRHow to Remove Specific Elements from Vector in R

How to Remove Specific Elements from Vector in R

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to remove specific elements from a vector in R:

#remove 'a', 'b', 'c' from my_vector
my_vector[! my_vector %in% c('a', 'b, 'c')]

The following examples show how to use this syntax in practice.

Example 1: Remove Elements from Character Vector 

The following code shows how to remove elements from a character vector in R:

#define vector
x #remove 'Mavs' and 'Spurs' from vector
x %in% c('Mavs', 'Spurs')]

#view updated vector
x

[1] "Nets"  "Hawks" "Bucks" "Suns" 

Notice that both ‘Mavs’ and ‘Spurs’ were removed from the vector.

Example 2: Remove Elements from Numeric Vector 

The following code shows how to remove elements from a numeric vector in R:

#define numeric vector
x #remove 1, 4, and 5
x %in% c(1, 4, 5)]

#view updated vector
x

[1]  2  2  2  3  7  7  8  9 12 12 13

Notice that every occurrence of the values 1, 4, and 5 were removed from the vector.

We can also specify a range of values that we’d like to remove from the numeric vector:

#define numeric vector
x #remove values between 2 and 10
x %in% 2:10]

#view updated vector
x

[1]  1 12 12 13

Notice that every value between 2 and 10 was removed from the vector.

We can also remove values greater or less than a specific number:

#define numeric vector
x #remove values less than 3 or greater than 10
x  10)]

#view updated vector
x

[1] 3 4 5 5 7 7 8 9

Additional Resources

How to Delete Data Frames in R
How to Delete Multiple Columns in R
How to Append Values to a Vector Using a Loop in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories