[R] sorting a data.frame (df) by a vector (which is not contained in the df) - unexpected behaviour of match and factor

Berend Hasselman bhh at xs4all.nl
Thu Dec 29 11:24:50 CET 2011

drflxms wrote
> Jeff,
> thanks a lot for your quick reply and the hint!
> Meanwhile I found a solution that works - at least for my case ;)
> The code to get the job done is
> df[order(match(df$level,desiredOrder)),]
> So we seem in need of one order statement more. I found this solution
> doing it stepwise:
> ## sorting the levels of the level column in the data.frame
> df$level <- factor(df$level,levels=desiredOrder)
> ## sorting the data frame by the newly sorted level column
> df[order(df$level),]
> Maybe this solution is of a help for someone else as well?
> But honestly I still do not exactly understand why
> df[match(df$level,desiredOrder),] doesn't work...

Read carefully


and  then do


and look carefully at the results. Then it should be clear.


View this message in context: http://r.789695.n4.nabble.com/sorting-a-data-frame-df-by-a-vector-which-is-not-contained-in-the-df-unexpected-behaviour-of-match-ar-tp4242326p4242400.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list