如何在 R 中查找向量中元素的索引?

r programmingserver side programmingprogramming

有三种方法可以查找向量中元素的索引。

示例

> x <- sample(1:10)
> x
[1] 8 10 9 6 2 1 4 7 5 3

使用 which

> which(x == 6)[[1]]
[1] 4

这里我们在向量 x 中找到了 6 的索引。

使用 match

> match(c(4,8),x)
[1] 7 1

这里我们找到了向量 x 中 4 和 8 的索引。

Using which with %in%
> which(x %in% c(2,4))
[1] 5 7

这里我们找到了向量 x 中 2 和 4 的索引。


相关文章