Home > Net >  Filter and select dataset in r
Filter and select dataset in r

Time:09-21

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!

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • r
  • Related