How to find the row corresponding to a nearest value in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To find the row corresponding to a nearest value in an R data frame, we can use which.min function after getting the absolute difference between the value and the column along with single square brackets for subsetting the row.

To understand how it works, check out the examples given below.

Example 1

Following snippet creates a sample data frame −

ID<-1:20
Score<-sample(50:100,20)
df1<-data.frame(ID,Score)
df1

Output

The following dataframe is created −

  ID  Score
1  1   85
2  2   91
3  3   73
4  4   77
5  5   98
6  6   53
7  7   59
8  8   74
9  9   88
10 10  84
11 11  82
12 12  94
13 13  56
14 14  76
15 15  89
16 16  71
17 17  52
18 18  64
19 19  69
20 20  63

To find the row corresponding to nearest 100 in df1, add the following code to the above snippet −

ID<-1:20
Score<-sample(50:100,20)
df1<-data.frame(ID,Score)
df1[which.min(abs(100-df1$Score)),]

Output

If you execute all the above given snippets as a single program, it generates the following Output −

  ID Score
5 5  98

Example 2

Following snippet creates a sample data frame −

Emp_ID<-sample(111111:999999,20)
Sal<-sample(20000:50000,20)
df2<-data.frame(Emp_ID,Sal)
df2

Output

The following dataframe is created −

   Emp_ID    Sal
1  234742   38090
2  584335   43409
3  850592   43036
4  841349   30627
5  628123   32998
6  297438   45053
7  635135   21746
8  866226   40546
9  457493   26573
10 779219   41954
11 933665   46539
12 162673   35816
13 608379   41035
14 256672   49987
15 605809   32840
16 996414   36487
17 910392   33479
18 964044   25177
19 934603   33697
20 171843   37909

To find the row corresponding to nearest 30000 in df2, add the following code to the above snippet −

Emp_ID<-sample(111111:999999,20)
Sal<-sample(20000:50000,20)
df2<-data.frame(Emp_ID,Sal)
df2[which.min(abs(30000-df2$Sal)),]

Output

If you execute all the above given snippets as a single program, it generates the following Output −

   Emp_ID  Sal
4  841349  30627
raja
Published on 03-Nov-2021 07:40:32

Advertisements