How to delete certain elements from a vector in the R language?
In R language, you can use the [-] operator to remove certain elements from a vector.
Here are some examples of removing elements from a vector:
- Remove one element from the vector.
vec <- c(1, 2, 3, 4, 5)
vec <- vec[-3]
print(vec)
# 输出:1 2 4 5
- Remove multiple elements from the vector.
vec <- c(1, 2, 3, 4, 5)
vec <- vec[c(-2, -4)]
print(vec)
# 输出:1 3 5
- Remove a segment of consecutive elements from the vector.
vec <- c(1, 2, 3, 4, 5)
vec <- vec[-2:-4]
print(vec)
# 输出:1 5
- Remove elements from a vector based on certain conditions.
vec <- c(1, 2, 3, 4, 5)
vec <- vec[vec != 3]
print(vec)
# 输出:1 2 4 5
Be careful, the length of the vector will decrease accordingly after deleting elements.