How to find the index of the minimum and maximum value of a vector in R?

R ProgrammingServer Side ProgrammingProgramming

While doing the data exploration in an analytical project, we sometimes need to find the index of some values, mostly the indices of minimum and maximum values to check whether the corresponding data row has some crucial information or we may neglect it. Also, these values sometimes transformed to another values based on the data characteristics if we don’t want to neglect them.

Example

> x<-1:25
> which(x==min(x))
[1] 1
> which(x==max(x))
[1] 25
> set.seed(2)
> x1<-sample(1:100,50,replace=TRUE)
> x1
 [1] 85 79 70  6  32  8 17 93 81 76 41 50 75 65  3 80 96 50 55
[20] 63  8 33 54 100 43 38 40 16 45 80  6 83  9 72 45  6 94  2
[39] 82 67  3  1  87 48 41 45 79 33 18  8
> which(x1==max(x1))
[1] 24
> which(x1==min(x1))
[1] 42
> x2<-sample(1:10,10,replace=TRUE)
> x2
[1] 4 5 2 5 6 7 2 6 4 4
> which(x2==min(x2))
[1] 3 7
> which(x2==max(x2))
[1] 6
> x3<-rpois(50,10)
> x3
 [1] 11  9 13 8 8  9 10 7 6 9 13 10  9  6 8 12 13 15  4 13 12 8  8 14 15
[26] 11 12  9 8 8 11  8 8 8 9  8  7 13 17 9  8 11 15 15  6 12 5 16 10  7
> which(x3==max(x3))
[1] 39
> which(x3==min(x3))
[1] 19
> x4<-rpois(5,10)
> x4
[1] 6 10 9 7 7
> which(x4==min(x4))
[1] 1
> which(x4==max(x4))
[1] 2
> x5<-rpois(200,10)
> x5
  [1] 12 16  8  8  6  9 13  9 13  8 10  7  7  8 12 15 10  8 14 11 12  3 10 14  8
 [26]  9  7  8 11  7 10  8  8  9  9  5 13  9 12  7  4 12 11 10 12 11  7  7  5 13
 [51]  9  4 13 13 12 10 11  7 10 13 12 10 11 14  6 15 11  7  4  9  5 10 12 14  6
 [76]  7 12 10  4 10  6 11  5 11 10 13  8 15  5  5 13 16  7  7 10  7  9 12  8 17
[101] 14 14 12  9  9  5 10  8  9 19 13 11 12  8 10 10  8  8 11  8  9  8 12 11  9
[126]  9 13  9 14  9  8 20 12  8 13 15 15  3 10 15  9 13  8 10 16 12 14  8 14 15
[151] 13 10 14  9  6 10 12  5  8 11 11  5 12  4 11  8  7 13  7 11  8  3  8 11 13
[176] 10 10  9  8 13 12 11 10 11 13 16 14  9 12  9  9 12 13  9 12  9 14 11 10 11
> which(x5==max(x5))
[1] 132
> which(x5==min(x5))
[1] 22 138 172
> x6<-runif(50,2,5)
> x6
 [1] 2.296152 2.637028 3.774618 3.552248 4.292848 4.011675 3.202220 2.190245
 [9] 3.124594 2.183614 4.511916 2.859132 4.388699 3.866623 3.947191 3.571981
[17] 4.781770 4.697633 4.242325 3.665438 3.067066 2.165258 4.817657 3.238631
[25] 4.970232 2.021909 4.757471 2.478177 2.519868 2.895012 4.392987 2.631473
[33] 4.306387 3.606730 3.647098 2.810375 4.820211 4.667225 4.768008 2.905660
[41] 3.079665 4.357212 2.927998 4.997810 2.089147 2.916278 2.381663 3.813988
[49] 2.971799 4.826013
> which(x6==min(x6))
[1] 26
> which(x6==max(x6))
[1] 44
> x7<-sample(200:1000,50,replace=TRUE)
> x7
[1] 505 336 509 265 716 492 202 703 916 209 283 323 780 451 237 909 636 853 426
[20] 220 747 234 612 583 939 870 426 391 600 910 945 382 449 477 910 851 871 432
[39] 338 880 629 952 526 234 739 798 589 220 914 746
> which(x7==max(x7))
[1] 42
> which(x7==min(x7))
[1] 7
raja
Published on 11-Aug-2020 12:26:13
Advertisements