[R] sort a data matrix by all the values and keep the names

hadley wickham h.wickham at gmail.com
Tue Sep 23 02:47:51 CEST 2008


On Mon, Sep 22, 2008 at 6:54 PM, zhihuali <lzhtom at hotmail.com> wrote:
>
> Dear all,
>
> If I have a data frame  x<-data.frame(x1=c(1,7),x2=c(4,6),x3=c(8,2)):
>   x1  x2  x3
>   1     4  8
>   7     6  2
>
> I want to sort the whole data and get this:
> x1 1
> x3  2
> x2  4
> x2  6
> x1   7
> x3   8
>
>  If I do sort(X), R reports:
> Error in order(list(x1 = c(1, 7), x2 = c(4, 6), x3 = c(8, 2)), decreasing = FALSE) :
>  unimplemented type 'list' in 'orderVector1'
>
> The only way I can sort all the data is by converting it to a matrix:
>> sort(as.matrix(x))
> [1] 1 2 4 6 7 8
>
> But now I lost all the names attributes.
>
> Is it possible to sort a data frame and keep all the names?

Here's one way:

dfm <- melt(x, id = c())
dfm[order(dfm$value), ]

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list