如何在 R 中过滤向量
在本文中,我们将讨论如何在 R 编程语言中过滤向量。
过滤向量意味着通过去除其他向量从向量中获取值,我们也可以说获取所需元素称为过滤。
方法 1:使用 %in%
在这里,我们可以使用 %in%运算符过滤向量中的元素
句法:
vec[vec %in% c(elements)]
在哪里
- vec 是输入向量
- 元素是我们想要得到的向量元素
示例: R 程序通过仅获取一些值来过滤向量
R
# create a vector with id and names
vector=c(1,2,3,4,5,"sravan","boby","ojaswi","gnanesh","rohith")
# display vector
print(vector)
print("=======")
# get the data - "sravan","rohith",3 from
# the vector
print(vector[vector %in% c("sravan","rohith",3)])
print("=======")
# get the data - "sravan","ojaswi",3,1,2 from
# the vector
print(vector[vector %in% c("sravan","ojaswi",3,1,2)])
print("=======")
# get the data - 1,2,3,4,5 from the vector
print(vector[vector %in% c(1,2,3,4,5)])
R
# create a vector with id and names
vector=c(1,2,3,4,5,"sravan","boby","ojaswi","gnanesh","rohith")
# display vector
print(vector)
print("=======")
# get the data where element not equal to 1
print(vector[vector != 1])
print("=======")
# get the data where element equal to 1
print(vector[vector == 1])
输出:
[1] “1” “2” “3” “4” “5” “sravan” “boby”
[8] “ojaswi” “gnanesh” “rohith”
[1] “=======”
[1] “3” “sravan” “rohith”
[1] “=======”
[1] “1” “2” “3” “sravan” “ojaswi”
[1] “=======”
[1] “1” “2” “3” “4” “5”
方法二:使用索引
我们还可以从索引运算符指定条件。
句法:
vector[condition(s)]
其中向量是输入向量,条件定义了过滤的条件。
示例:使用条件过滤向量的 R 程序
电阻
# create a vector with id and names
vector=c(1,2,3,4,5,"sravan","boby","ojaswi","gnanesh","rohith")
# display vector
print(vector)
print("=======")
# get the data where element not equal to 1
print(vector[vector != 1])
print("=======")
# get the data where element equal to 1
print(vector[vector == 1])
输出:
[1] “1” “2” “3” “4” “5” “sravan” “boby”
[8] “ojaswi” “gnanesh” “rohith”
[1] “=======”
[1] “2” “3” “4” “5” “sravan” “boby” “ojaswi”
[8] “gnanesh” “rohith”
[1] “=======”
[1] “1”