现在位置: 首页 > R 教程 > 正文

R which() 函数 - 条件索引查找

R 语言实例 R 语言实例

R which() 函数用于返回满足条件的元素的索引位置。

which() 在数据筛选和定位特定元素时非常常用。

which() 函数语法格式如下:

which(x, arr.ind = FALSE)

参数说明:

  • x 逻辑向量或包含逻辑条件的表达式。

  • arr.ind 用于矩阵/数组时,是否返回行列索引,默认 FALSE。

实例

scores <- c(55, 62, 78, 85, 92, 70, 88, 95, 60, 82)

# 找出及格(>=60)的索引
pass_idx <- which(scores >= 60)
print("及格学生的索引:")
print(pass_idx)

# 通过索引获取对应的成绩
print("及格学生的成绩:")
print(scores[pass_idx])

# 查找最大值的位置
max_idx <- which.max(scores)
print(paste("最高分索引:", max_idx, "成绩:", scores[max_idx]))

# 查找最小值的位置
min_idx <- which.min(scores)
print(paste("最低分索引:", min_idx, "成绩:", scores[min_idx]))

执行以上代码输出结果为:

[1] "及格学生的索引:"
[1]  2  3  4  5  6  7  8 10
[1] "及格学生的成绩:"
[1] 62 78 85 92 70 88 95 82
[1] "最高分索引: 8 成绩: 95"
[1] "最低分索引: 1 成绩: 55"

which() 也适用于矩阵,结合 arr.ind = TRUE 可以返回行列坐标:

实例

# 创建矩阵
m <- matrix(1:12, nrow = 3)
print("矩阵:")
print(m)

# 找出大于 8 的元素的行列位置
positions <- which(m > 8, arr.ind = TRUE)
print("大于 8 的元素位置(行, 列):")
print(positions)

执行以上代码输出结果为:

[1] "矩阵:"
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
[1] "大于 8 的元素位置(行, 列):"
     row col
[1,]   1   4
[2,]   2   4
[3,]   3   3
[4,]   3   4

R 语言实例 R 语言实例