R语言 which()函数
R编程语言中的 which() 函数用于返回逻辑向量中指定值的位置。
语法: which(x, arr.ind, useNames)
参数: 该函数接受一些参数,如下图所示。
- X: 这是指定的输入逻辑向量
- Arr.ind: 如果x是一个数组,这个参数,返回数组的索引。
- useNames: 这个参数表示一个数组的维度名称。
返回值: 该函数返回指定值在逻辑向量中的位置。
例1: Which()函数应用于字母表
在下面的例子中,which()函数返回指定字母的字母表位置。例如,a是字母表序列中的第一个字母,所以返回1,z是序列中的最后一个字母,所以返回26。
# R program to illustrate
# which() function
# Calling the which function
# to return alphabetical position
# of the given alphabet
which(letters == "a")
which(letters == "d")
which(letters == "z")
which(letters == "p")
which(letters == "g")
输出:
[1] 1
[1] 4
[1] 26
[1] 16
[1] 7
例2: which()函数与向量的关系
在下面的例子中,在which()函数的帮助下,指定向量的一些元素的位置被返回。
# R program to illustrate
# which() function
# Creating a vector of some elements
vector <- c(3, 5, 1, 6, 12, 4)
# Getting the position of element 12
# in the above vector
which(vector == 12)
# Getting the position of element 1
# in the above vector
which(vector == 1)
# Getting the position of element 6
# in the above vector
which(vector == 6)
# Getting the position of elements
# those are greater than 5
which(vector > 5)
输出
[1] 5
[1] 3
[1] 4
[1] 4 5
例3:which()函数与数据框架
在下面的例子中,which()函数被用来查找数据框架中的数值列。
一个Iris数据集被用作数据框架,其中包含4列数值和1列分类值,即物种。which()函数从数据集中找到含有数字值的列名。
# Considering “Iris” dataset
data_set <- datasets::iris
# Printing the Iris dataset values
# along with its 5 columns out of which
# 4 columns are numerical and 1 is categorical
# (Species)
head(data_set)
# Calling the which() function over
# the above specified data set that
# returns the columns with numeric values
Result <- which(sapply(data_set, is.numeric))
# Printing the columns with numeric values
colnames(data_set)[Result]
输出
例4:which()函数与矩阵的关系
在下面的例子中,which()函数被用来寻找一个元素在指定矩阵中的位置。
这里要计算的是数值2在指定矩阵中的位置。
# Creating a matrix of 3 columns and 4 rows
Matrix <- matrix(rep(c(1, 2, 3), 4), nrow = 4)
# Printing the entire matrix with its values
Matrix
# Calling the which() function to find the
# position of value 2 in the above matrix
which(Matrix == 2, arr.ind = T)
输出