R语言 获取数组中指定值的索引 – arrayInd()函数
R语言中的 arrayInd() 函数是用来获取作为参数传递给函数的值的索引的。这个函数接收值和要搜索的数组,并返回找到的每个匹配值的索引。
语法: arrayInd(values, dim(x))
参数:
values: 要搜索的值或值的向量
dim(x): 要搜索的阵列
x: 阵列名称
例1 :
# R program to illustrate
# the use of arrayInd() function
# Creating an array
x <- array(1:9, dim = c(2, 3))
x
# Creating vector of values to be found
x1 <- c(5, 4, 6)
# Calling arrayInd() function
arrayInd(x1, dim(x))
输出
[, 1] [, 2] [, 3]
[1, ] 1 3 5
[2, ] 2 4 6
[, 1] [, 2]
[1, ] 1 3
[2, ] 2 2
[3, ] 2 3
例2 :
# R program to illustrate
# the use of arrayInd() function
# Creating an array
x <- array(1:9, dim = c(3, 3))
x
# Extracting values using which() function
x1 <- which(x > 3 & x < 8)
# Calling arrayInd() function
arrayInd(x1, dim(x))
输出
[, 1] [, 2] [, 3]
[1, ] 1 4 7
[2, ] 2 5 8
[3, ] 3 6 9
[, 1] [, 2]
[1, ] 1 2
[2, ] 2 2
[3, ] 3 2
[4, ] 1 3
在这里,在上面的代码中,arrayInd()函数返回所有由which()函数返回的值的索引。