R语言 如何过滤一个向量
在这篇文章中,我们将讨论如何在R编程语言中过滤一个向量。
过滤一个向量意味着从向量中去除其他的值,我们也可以说,获得所需的元素被称为过滤。
方法1:使用%in%
这里我们可以通过使用%in%操作符来过滤向量中的元素
语法 。
vec[vec %in% c(elements)]
其中
- vec是输入向量
- 元素是我们想得到的向量元素
例子: 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)])
输出 。
[1] "1" "2" "3" "4" "5" "sravan" "boby"
[8] "Ojaswi" "Gnanesh" "Roshith"
[1] "======="
[1] "3" "sravan" "rohith"
[1] "======="
[1] "1" "2" "3" "Sravan" "Ojaswi"
[1] "======="
[1] "1" "2" "3" "4" "5"
方法2:使用索引
我们也可以从索引运算符中指定条件。
语法 。
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" "Roshith"
[1] "======="
[1] "2" "3" "4" "5" "Sravan" "Boby" "Ojaswi"
[8] "Gnanesh" "Roshith"
[1] "======="
[1] "1"