How to determine the row that have min and max values in an R data frame column?
-
10-09-2020 - |
Question
How to determine the row that have min and max values in an R data frame column?
In data analysis, often we require to determine the minimum and maximum values because these values help us to understand the limits of a column or variable under consideration. This can be done by using which.max for maximum and which.min for minimum with single square brackets to extract the rows.
Example
Consider the below data frame −
x1<-LETTERS[1:20] x2<-rpois(20,5) x3<-rexp(20,2) x4<-rexp(20,5) df1<-data.frame(x1,x2,x3,x4) df1
Output
x1 x2 x3 x4 1 A 7 0.56888750 0.10767756 2 B 7 0.04138254 0.01507087 3 C 3 0.82145385 0.02568754 4 D 4 0.07945021 0.51976803 5 E 7 0.73930797 0.41403820 6 F 7 0.05651587 0.04107620 7 G 4 0.11206284 0.55322510 8 H 3 0.33525532 0.29126855 9 I 6 0.76841536 0.55258446 10 J 2 0.96441097 0.29656683 11 K 1 0.10678610 0.05482085 12 L 14 0.28394648 0.15006675 13 M 1 0.96666190 0.21007950 14 N 4 1.80137393 0.07231502 15 O 8 0.65978932 0.19218883 16 P 6 0.46538207 0.13262744 17 Q 4 0.15772843 0.31552748 18 R 6 0.07239103 0.38449618 19 S 7 0.46414726 0.04460063 20 T 4 0.12917123 0.76904118
Determining the rows that have maximum and minimum values for a particular column −
Example
df1[which.max(df1$x2),]
Output
x1 x2 x3 x4 12 L 14 0.2839465 0.1500667
Example
df1[which.min(df1$x2),]
Output
x1 x2 x3 x4 11 K 1 0.1067861 0.05482085
Example
df1[which.min(df1$x3),]
Output
x1 x2 x3 x4 2 B 7 0.04138254 0.01507087
Example
df1[which.min(df1$x4),]
Output
x1 x2 x3 x4 2 B 7 0.04138254 0.01507087
Let’s have a look at another example −
Example
y1<-sample(1:100,20) y2<-sample(1:10,20,replace=TRUE) y3<-sample(20:100,20,replace=TRUE) y4<-sample(50:100,20,replace=TRUE) y5<-rpois(20,15) df2<-data.frame(y1,y2,y3,y4,y5) df2
Output
y1 y2 y3 y4 y5 1 20 10 64 81 19 2 100 5 29 61 20 3 93 4 61 68 14 4 84 2 43 76 17 5 94 1 37 81 6 6 41 1 100 76 19 7 8 5 78 79 19 8 39 2 28 53 19 9 74 2 72 73 12 10 81 3 30 77 15 11 63 5 27 52 21 12 82 6 24 95 19 13 11 10 48 89 12 14 2 3 69 55 13 15 19 3 89 85 18 16 77 1 93 91 18 17 13 8 45 97 13 18 31 1 92 79 9 19 30 4 30 97 15 20 22 8 25 59 19
Example
df2[which.min(df2$y1),]
Output
y1 y2 y3 y4 y5 14 2 3 69 55 13
Example
df2[which.min(df2$y2),]
Output
y1 y2 y3 y4 y5 5 94 1 37 81 6
Example
df2[which.max(df2$y2),]
Output
y1 y2 y3 y4 y5 1 20 10 64 81 19
Example
df2[which.min(df2$y3),]
Output
y1 y2 y3 y4 y5 12 82 6 24 95 19
Example
df2[which.min(df2$y5),]
Output
y1 y2 y3 y4 y5 5 94 1 37 81 6
Advertisements
Not affiliated with Tutorialspoint