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)

It sorts vector by its index:

>x <- c(1,2.3,2,3,4,8,12,43,-4,-1,NA)
>order(x)

[1]  9 10  1  3  2  4  5  6  7  8 11

>order(x,decreasing=TRUE)

[1]  8  7  6  5  4  2  3  1 10  9 11

>order(x,decreasing=TRUE, na.last=TRUE)

[1]  8  7  6  5  4  2  3  1 10  9 11

>order(x,decreasing=TRUE, na.last=FALSE)

[1] 11  8  7  6  5  4  2  3  1 10  9

sort() function can sort vector by its values:

>x <- c(1,2.3,2,3,4,8,12,43,-4,-1,NA)
>sort(x)

[1] -4.0 -1.0 1.0 2.0 2.3 3.0 4.0 8.0 12.0 43.0

>sort(x,decreasing=TRUE)

[1] 43.0 12.0 8.0 4.0 3.0 2.3 2.0 1.0 -1.0 -4.0

>sort(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

>sort(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


endmemo.com © 2024  | Terms of Use | Privacy | Home