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:

  1. Remove one element from the vector.
vec <- c(1, 2, 3, 4, 5)
vec <- vec[-3]
print(vec)
# 输出:1 2 4 5
  1. Remove multiple elements from the vector.
vec <- c(1, 2, 3, 4, 5)
vec <- vec[c(-2, -4)]
print(vec)
# 输出:1 3 5
  1. Remove a segment of consecutive elements from the vector.
vec <- c(1, 2, 3, 4, 5)
vec <- vec[-2:-4]
print(vec)
# 输出:1 5
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds