To remove items from a vector based on a condition in R, you can use the subset
function or indexing with logical vectors.
In this example,
vec
with some integer values.subset
function to subset the vector based on a condition. The condition is specified using a logical expression where we want to keep elements less than 30.vec_new
.vec <- c(10, 20, 30, 40, 50)
vec_new <- subset(vec, vec < 30)
print(vec_new)
[1] 10 20
In this example,
vec
with some integer values.vec_new
.vec <- c(10, 20, 30, 40, 50)
logical_vector <- vec < 30
vec_new <- vec[logical_vector]
print(vec_new)
[1] 10 20
In this tutorial, we learned How to Remove Items from Vector based on a Condition in R language with well detailed examples.