📜  在 R 编程中返回逻辑对象的真实索引 - which()函数

📅  最后修改于: 2022-05-13 01:54:42.920000             🧑  作者: Mango

在 R 编程中返回逻辑对象的真实索引 - which()函数

R 语言中的which()函数用于返回对象的索引,该索引对于作为参数传递的逻辑操作返回 true。

示例 1:

# R program to illustrate 
# the use of which() function
  
# Create a matrix
x <- matrix(1:9, 3, 3)
x
  
# Calling which() function
which(x %% 2 == 0, arr.ind = TRUE)

输出:

[, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
     row col
[1, ]   2   1
[2, ]   1   2
[3, ]   3   2
[4, ]   2   3

在这里,在上面的代码中, which()函数返回矩阵中所有偶数的索引。

示例 2:

# R program to illustrate 
# the use of which() function
  
# Using predefined dataset
BOD
  
# Calling which() function
which(BOD$demand == 19, arr.ind = TRUE)

输出:

Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8
[1] 3