sort a data frame based on multiple columns in R

This question already has an answer here:

  • How to sort a dataframe by multiple column(s)? 16 answers

  • To sort in ascending order:

    Use dplyr like this:

    library(dplyr)
    df <- df %>% arrange(type, frequency, word)
    

    Just arrange the variables in the order you would like to sort.

    To sort in descending order:

    Just use a negative sign in front of the variable you want to sort in reverse order. Like this.

    df %>% arrange(-type, frequency, word)
    

    Working with text...

    If you want to try sorting text in reverse order using the method above, you may get an error. To arrange categorical variables, wrap the variable around desc(), as such:

    df %>% arrange(desc(word))
    
    链接地址: http://www.djcxy.com/p/70860.html

    上一篇: 根据模式重新排列数据

    下一篇: 根据R中的多个列对数据框进行排序