0

Using the mtcar dataset I want to find the top 2 cars with the highest mileage and after knowing that information I want to create a new data frame that has info of only those 2 cars with all the remaining info like horsepower, gear, cylinder, and so on. Please let me know how could I do that

cars<-mtcars %>% 
          group_by(mpg) %>% 
          count(mpg)

So with this, I get 32.9 and 32.4 as best mpg now how do I add all the other info in a new data frame that has info about these 2 cars. Please let me know. Thank you!

akrun
  • 874,273
  • 37
  • 540
  • 662
Don Krieg
  • 27
  • 4
  • `dplyr::count` counts how many times a group occurs. It's not going to give you a maximum value – camille Sep 21 '21 at 02:12
  • Also see https://stackoverflow.com/q/27766054/5325862, https://stackoverflow.com/q/63793757/5325862, and https://stackoverflow.com/q/53994497/5325862 – camille Sep 21 '21 at 02:21

2 Answers2

1

We may use slice_max

library(dplyr)
mtcars %>% 
    slice_max(n = 2, order_by = "mpg")

Or use arrange and slice

mtcars %>% 
    arrange(desc(mpg)) %>%
    slice_head(n = 2)

-output

                 mpg cyl disp hp drat    wt  qsec vs am gear carb
Toyota Corolla 33.9   4 71.1 65 4.22 1.835 19.90  1  1    4    1
Fiat 128       32.4   4 78.7 66 4.08 2.200 19.47  1  1    4    1
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You could use top_n from dplyr.

library(dplyr)

top2mpg <- mtcars %>% top_n(2, mpg)
mpg cyl disp hp drat wt qsec vs am gear carb FIELD13
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
norie
  • 9,609
  • 2
  • 11
  • 18