Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort data frame while keep original row id and dimension

Tags:

sorting

r

numeric

What I want to do is very simple. I would like to sort this data frame df:

    Signal
1   18
2   0.043
3   549
4   9998
5   2.342

By Signal, in order to obtain this:

    Signal
4   9998
3   549
1   18
5   2.342
2   0.043

It's important that the original row IDs are conserved.

I tried sort(df$Signal) and df[sort(df$Signal),] but it gives me a list.

like image 371
biohazard Avatar asked Mar 18 '14 01:03

biohazard


1 Answers

As df is a function in package stats, I will call your data frame d.

order does indeed do the job, but you need to supply drop=FALSE to [ to prevent getting a vector (dropping a dimension). The dimension is dropped by default when possible, and here it is possible.

d[order(d$Signal, decreasing=TRUE),, drop=FALSE]
    Signal
4 9998.000
3  549.000
1   18.000
5    2.342
2    0.043
like image 186
Matthew Lundberg Avatar answered Sep 28 '22 23:09

Matthew Lundberg