Function reorder in R and ordering values

r, sorting

Solution

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 values of the factor variable(`group` in your case).

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 your 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        # <--------------------------------

Problem

I'm trying the following function: ``` stest <- data.frame(group=c("John", "Jane", "James"), mean=c(3, 5, 1)) transform(stest, group = reorder(group, mean)) ``` And expect the output be ordered by `mean`. Instead, I get: ``` group mean 1 John 3 2 Jane 5 3 James 1 ``` That is, same order as in the original dataframe. Do I miss something? How to order a data frame correctly by one of its numerical variables? Recommendations around is about using `reorder`, but I can't make it work as expected. Can any loaded packages interfere?

Original source

Related problems