Jakob Kaare-Rasmussen
Jakob Kaare-Rasmussen

Reputation: 47

Extracting a range of values from a list, but excluding a few in R

If I have a vector with the integers from 1 to 100 and I want to extract the integers from 30 to 60 but not include 40 how do I do that? I can do each part on its own:

y<-1:100
y[30:60]
y[-40]

But I can't find a way to do both at once. How do I do that?

Note that I am NOT looking for a solution like this:

y[c(30:39,41:60)]

but instead, a solution that explicitly extracts the value I don't want.

Upvotes: 0

Views: 598

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101129

Here is another base R option using %in% and &

y[(u <- seq_along(y)) %in% 30:60 & u != 40]

Upvotes: 1

akrun
akrun

Reputation: 886948

An option is setdiff

y[setdiff(30:60, 40)]

It can also be a vector of values

y[setdiff(30:60, c(40, 47, 51))]

Upvotes: 2

Related Questions