在 R 编程中获取数组指定值的索引 – arrayInd()函数
R 语言中的arrayInd()
函数用于获取作为参数传递给函数的值的索引。此函数获取值和要在其中搜索值的数组,并返回找到的每个匹配项的索引。
Syntax: arrayInd(values, dim(x))
Parameters:
values: value or vector of values to be searched
dim(x): array to be searched
x: Array name
示例 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()
()函数返回的所有值的索引。