Falrach
Falrach

Reputation: 155

Remove values from a vector based on a condition

Suppose I have a vector x <- c(-10,10) and I want to remove the values from the vector which absolute value is larger than 8, how can I achieve that?

I do not want to delete the values by knowing the exact values, which would be c(-10, -9 , 9 , 10), like in this post: How to delete multiple values from a vector?

Upvotes: 0

Views: 2550

Answers (2)

Filipe Lauar
Filipe Lauar

Reputation: 444

this solve your problem:

x <- x[abs(x) <= 8]

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 102700

You have many ways to make it

x <- x[abs(x) <= 8]

or

x <- subset(x,abs(x)<=8)

or

x <- x[-which(abs(x)>8)]

or

x <- na.omit(ifelse(abs(x) > 8,NA,x))

Upvotes: 4

Related Questions