R语言中利用which函数返回向量中最大值、最小值、指定值的索引

 

001、

> dat <- c(3, 7, 9, 1, 2, 3, 4, 4, 7, 5)
> dat
 [1] 3 7 9 1 2 3 4 4 7 5
> which.max(dat)       ## 返回最大值的索引
[1] 3
> which.min(dat)       ## 返回最小值的索引
[1] 4
> which(dat == 7)      ## 返回值等于7的索引
[1] 2 9
> which(dat == 2)      ## 返回值等于2的索引
[1] 5

 

> dat <- c(3, 7, 9, 1, 2, 3, 4, 4, 7, 5)
> dat
 [1] 3 7 9 1 2 3 4 4 7 5
> which(dat < 3)       ## 返回小于3的值的索引
[1] 4 5
> which(dat > 5)       ## 返回大于5的值的索引
[1] 2 3 9

 

002、返回从小到大、从大到小排列的索引

> dat <- c(3, 7, 9, 1, 2, 3, 4, 4, 7, 5)
> dat
 [1] 3 7 9 1 2 3 4 4 7 5
> order(dat)            ## 返回从小到大排序的索引
 [1]  4  5  1  6  7  8 10  2  9  3
> order(dat, decreasing = T)    ## 返回从大到小排序的索引
 [1]  3  2  9 10  7  8  1  6  5  4

 

003、返回重复值的索引

> dat <- c(3, 7, 9, 1, 2, 3, 4, 4, 7, 5)
> dat
 [1] 3 7 9 1 2 3 4 4 7 5
> which(duplicated(dat))      ## 返回重复值的索引
[1] 6 8 9

 

posted @ 2022-04-25 22:28  小鲨鱼2018  阅读(1126)  评论(0编辑  收藏  举报