R order Function


order() function sorts a vector, matrix or data frame.

order(x, decreasing = FALSE, na.last = NA, ...)

x: vector
decreasing: decrease or not
na.last: if TRUE, NAs are put at last position, FALSE at first, if NA, remove them (default)
...

Sort Vectors:
>x <- c(1,2.3,2,3,4,8,12,43,-4,-1,NA)
>order(x)
 [1] -4.0 -1.0  1.0  2.0  2.3  3.0  4.0  8.0 12.0 43.0

>order(x,decreasing=TRUE)
 [1] 43.0 12.0  8.0  4.0  3.0  2.3  2.0  1.0 -1.0 -4.0

>order(x,decreasing=TRUE, na.last=TRUE)
 [1] 43.0 12.0  8.0  4.0  3.0  2.3  2.0  1.0 -1.0 -4.0   NA

>order(x,decreasing=TRUE, na.last=FALSE)
 [1]   NA 43.0 12.0  8.0  4.0  3.0  2.3  2.0  1.0 -1.0 -4.0

Sort Matrix by one column, following is a csv file example.


>x <- read.csv("ordermatrix.csv",header=T,sep=",");
>x <- x[order(x[,4]),];
>x



Order data frame:
>BOD     #R built-in dataset, Biochemical Oxygen Demand
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

Sort by "demand" column:
>BOD[with(BOD,order(demand)),]
  Time demand
1    1    8.3
2    2   10.3
5    5   15.6
4    4   16.0
3    3   19.0
6    7   19.8