[R] Non-standard sorts on vectors

Phil Spector spector at stat.berkeley.edu
Fri Aug 27 00:16:42 CEST 2010


Here's one possibility:

> sort.v<-c(Lake=1,Shoreline=2,Floodplain=3)
> test.df[order(sort.v[as.character(test.df$Zone)]),]
         Zone Cover
2       Lake    60
3  Shoreline    70
1 Floodplain    50

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu



On Thu, 26 Aug 2010, chipmaney wrote:

>
> I have a dataset I need to sort:
>
> test.df<-data.frame(Zone=c("Floodplain", "Lake",
> "Shoreline"),Cover=c(50,60,70))
>
> However, I don't want it sorted ascending/descending but in an order that I
> define via a vector:
>
> sort.v<-data.frame(c("Lake","Shoreline","Floodplain"))
>
> I realize I could probably just create the vector of [factors] in the order
> I want, then assign the value:
>
> sort.v$Cover<-test.df$Cover
>
> However, this is inefficient.  Is there source code or a syntactical trick
> that will do the same more efficiently?  Note: I have investigated order()
> and sort(), but neither seems to have an argument for defining the sorting
> order.
>
> Thanks in advance, Chipper
>
> -- 
> View this message in context: http://r.789695.n4.nabble.com/Non-standard-sorts-on-vectors-tp2340431p2340431.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list