Maurice
Maurice

Reputation: 53

How to find which row has the highest value for a specific column in a dataframe?

I don't know how to find which row would give me the highest value for a specific column in a data frame

For example below.

mtcars 
               mpg cyl disp  hp drat   wt ... 
Mazda RX4     21.0   6  160 110 3.90 2.62 ... 
Mazda RX4 Wag 21.0   6  160 110 3.90 2.88 ... 
Datsun 710    22.8   4  108  93 3.85 2.32 ...

I am focusing on the wt column and trying to see which one has the highest value, which would be the Mazda RX4 Wag of 2.88

Also how do I find specific values using names instead of vectors? For example Mazda RX4 Wag wt. I have tried df[df$Mazda RX4 Wag,df$wt] but gives me an error.

Thanks

Upvotes: 3

Views: 6088

Answers (4)

Andrew Haynes
Andrew Haynes

Reputation: 2640

If you want the row number of the maximum value, use which.max():

> which.max(mtcars$wt)
[1] 16

To get all the information in that row, use it to subset your data frame:

> mtcars[which.max(mtcars$wt),]
                     mpg cyl disp  hp drat    wt  qsec vs am gear carb
Lincoln Continental 10.4   8  460 215    3 5.424 17.82  0  0    3    4

To select elements of a data.frame by name just insert them as strings. If you want multiple rows or columns you will have to put them into a vector with c().

> mtcars['Mazda RX4 Wag','wt']
[1] 2.875

Upvotes: 0

Sowmya S. Manian
Sowmya S. Manian

Reputation: 3833

drop = FALSE lets you print the car name i.e. the row name where you have highest or lowest wt value

1. Highest Value of wt column

To print maximum (Using max() function) or highest value of wt column.

 mtcars[mtcars$wt == max(mtcars$wt), "wt", drop = FALSE]
 #                        wt
 # Lincoln Continental 5.424

OR

Use which.max() as suggested by ycw.

  mtcars[which.max(mtcars$wt), "wt", drop = FALSE]
  #                        wt
  # Lincoln Continental 5.424

2. Lowest value of wt column

To print minimum (using min() function) or lowest value of wt column

 mtcars[mtcars$wt == min(mtcars$wt), "wt", drop = FALSE]
 #                 wt
 # Lotus Europa 1.513

OR

Use which.min() as suggested by ycw.

 mtcars[which.min(mtcars$wt), "wt", drop = FALSE]
 #                 wt
 # Lotus Europa 1.513

Upvotes: 1

www
www

Reputation: 39154

To your fist question.

subset(mtcars, wt == max(wt))[, "wt"]
[1] 5.424

To your second question

mtcars[row.names(mtcars) == "Mazda RX4 Wag", "wt"]
[1] 2.875

Upvotes: 2

Sam
Sam

Reputation: 654

Maybe something like this:

which(name.of.datatable == max(name.of.datatable[, 7]), arr.ind = T)

Upvotes: 0

Related Questions