Function reorder in R and ordering values

This question already has an answer here:

  • How to sort a dataframe by multiple column(s)? 16 answers
  • Order Bars in ggplot2 bar graph 9 answers

  • from the documentation

    reorder is a generic function. The "default" method treats its first argument as a categorical variable, and reorders its levels based on the values of a second variable, usually numeric.

    note reordering levels, not the column

    compare:

    levels(stest$group)
    [1] "James" "Jane"  "John" 
    

    with

    >  reorder(stest$group, c(1,2,3))
    [1] John  Jane  James
    attr(,"scores")
    James  Jane  John 
        3     2     1 
    Levels: John Jane James
    

    EDIT 1

    From you comment:

    "@Chargaff Yep, it returns the right order, but when I'm trying to use this dataframe in ggplot, ggplot still plots it in the previous order."

    it seems you do actually want to reorder levels for a ggplot. I suggest you do:

    stest$group <- reorder(stest$group, stest$mean)
    

    EDIT 2

    RE your last comment that the above line of code has "no effect". Clearly it does:

    > stest$group
    [1] John  Jane  James
    Levels: James Jane John         # <-------------------------------
    > stest$group <- reorder(stest$group, stest$mean)              # |
    > stest$group                                                  # |
    [1] John  Jane  James                                          # |
    attr(,"scores")                                                # | DIFFERENT :)
    James  Jane  John                                              # |
        1     5     3                                              # | 
    Levels: James John Jane        # <--------------------------------
    

    I think you are wanting the order function which returns an index, not reorder which is used to change the order of factor levels. This would do it.

    > stest[order(stest$mean),]
    

    I've found my mistake thanks to user1317221_G and others.

    The correct code that would order my dataset is:

    stest$group <- reorder(stest$group, stest$mean, FUN=identity)
    

    While

    stest$group <- reorder(stest$group, stest$mean)
    

    didn't order my dataframe. Not sure why FUN = mean didn't work, but I had to specify identity .

    Possible reason is this: Reordering factor gives different results, depending on which packages are loaded

    UPDATE

    It's not enough to have the first line of code. reorder does not coerce the second argument to factors, thus final ordering may be incomplete (eg, higher values below lower values in descending order).

    Therefore, to be sure you have the right order:

    stest$group <- reorder(stest$group, as.factor(stest$mean), FUN=identity)
    
    链接地址: http://www.djcxy.com/p/70842.html

    上一篇: 重新排序和重塑R中的列

    下一篇: R中的函数重新排序和排序值