Make a table showing the 10 largest values of a variable in R?

前端 未结 4 2130
温柔的废话
温柔的废话 2021-02-04 15:03

I want to make a simple table that showcases the largest 10 values for a given variable in my dataset, as well as 4 other variables for each observation, so basically a small su

4条回答
  •  天涯浪人
    2021-02-04 15:55

    You can get the highest values of a vector using the code below:

    my_vec <- c(1:100)
    tail(sort(my_vec),10)
    

    So if you want to use this method as a data frame filter you could do:

    data(mtcars)
    mtcars[mtcars$mpg %in% tail(sort(mtcars$mpg),4),]
    

    which would produce:

    > mtcars[mtcars$mpg %in% tail(sort(mtcars$mpg),4),]
                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
    Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
    Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
    Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
    Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2
    

提交回复
热议问题