Search code examples
rsortingrow

Sorting a column in descending order in R excluding the first row


I have a dataframe with 5 columns and a very large dataset. I want to sort by column 3. How do you sort everything after the first row? (When calling this function I want to end it with nrows)

Example output:

Original:

4
7
9
6
8

New:

4
9
8
7
6

Thanks!


Solution

  • If I'm correctly understanding what you want to do, this approach should work:

    z <- data.frame(x1 = seq(10), x2 = rep(c(2,3), 5), x3 = seq(14, 23))
    zsub <- z[2:nrow(z),]
    zsub <- zsub[order(-zsub[,3]),]
    znew <- rbind(z[1,], zsub)
    

    Basically, snip off the rows you want to sort, sort them in descending order on column 3, then reattach the first row.

    And here's a piped version using dplyr, so you don't clutter the workspace with extra objects:

    library(dplyr)
    z <- z %>%
        slice(2:nrow(z)) %>%
        arrange(-x3) %>%
        rbind(slice(z, 1), .)