How to find the index of the nearest smallest number in an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

To find the index of the nearest smallest number in an R data frame column, we can use which function along with subsetting for the value for which we want to find the index of the nearest smallest number. To understand how it can be done check out the below examples.

Example1

Consider the below data frame −

 Live Demo

ID<-1:20
Response<-rpois(20,10)
df1<-data.frame(ID,Response)
df1

Output

  ID Response
1  1   14
2  2   3
3  3   9
4  4   8
5  5   12
6  6   7
7  7   16
8  8   6
9  9   7
10 10  7
11 11  9
12 12  12
13 13  7
14 14  6
15 15  12
16 16  14
17 17  13
18 18  12
19 19  11
20 20  10

x1<-5

Finding the index of value in Response column that is nearest smallest to value in x1 −

which(df1$Response==max(df1$Response[df1$Response<=x1]))
[1] 2

Example2

Y<-rpois(20,10)
df2<-data.frame(group,Y)
df2

Output

  group Y
1  c    7
2  a    8
3  b    11
4  b    8
5  b    11
6  b    9
7  c    6
8  b    8
9  b    11
10 c    10
11 c    9
12 b    10
13 a    12
14 a    12
15 c    9
16 b    11
17 a    12
18 b    7
19 c    8
20 b    12

x2<-10

Finding the index of value in Response column that is nearest smallest to value in x1 −

which(df2$Y==max(df2$Y[df2$Y<=x2]))
[1] 10 12
raja
Published on 06-Mar-2021 13:54:07
Advertisements