Convenience Methods to Sort Data Frames and Data Sets

Description

The methods below return a sorted version of the data frame or data set, given as first argument.

Usage

## S4 method for signature 'data.frame'
sort(x,decreasing=FALSE,by=NULL,na.last=NA,...)
## S4 method for signature 'data.set'
sort(x,decreasing=FALSE,by=NULL,na.last=NA,...)

Arguments

x

a data frame or data set.

decreasing

a logical value, should sorting be in increasing or decreasing order?

by

a character name of variable names, by which to sort; a formula giving the variables, by which to sort; NULL, in which case, the data frame / data set is sorted by all of its variables.

na.last

for controlling the treatment of ‘NA’s. If ‘TRUE’, missing values in the data are put last; if ‘FALSE’, they are put first; if ‘NA’, they are removed

...

other arguments, currently ignored.

Value

A sorted copy of x.

Examples

DF <- data.frame(
       a = sample(1:2,size=20,replace=TRUE),
       b = sample(1:4,size=20,replace=TRUE))
sort(DF)
   a b
3  1 1
13 1 1
1  1 2
4  1 2
15 1 2
14 1 3
16 1 3
19 1 3
2  2 1
7  2 1
10 2 1
18 2 1
6  2 2
9  2 2
5  2 3
8  2 3
20 2 3
11 2 4
12 2 4
17 2 4
sort(DF,by=~a+b)
   a b
3  1 1
13 1 1
2  2 1
7  2 1
10 2 1
18 2 1
1  1 2
4  1 2
15 1 2
6  2 2
9  2 2
14 1 3
16 1 3
19 1 3
5  2 3
8  2 3
20 2 3
11 2 4
12 2 4
17 2 4
sort(DF,by=~b+a)
   a b
3  1 1
13 1 1
1  1 2
4  1 2
15 1 2
14 1 3
16 1 3
19 1 3
2  2 1
7  2 1
10 2 1
18 2 1
6  2 2
9  2 2
5  2 3
8  2 3
20 2 3
11 2 4
12 2 4
17 2 4
sort(DF,by=c("b","a"))
   a b
3  1 1
13 1 1
2  2 1
7  2 1
10 2 1
18 2 1
1  1 2
4  1 2
15 1 2
6  2 2
9  2 2
14 1 3
16 1 3
19 1 3
5  2 3
8  2 3
20 2 3
11 2 4
12 2 4
17 2 4
sort(DF,by=c("a","b"))
   a b
3  1 1
13 1 1
1  1 2
4  1 2
15 1 2
14 1 3
16 1 3
19 1 3
2  2 1
7  2 1
10 2 1
18 2 1
6  2 2
9  2 2
5  2 3
8  2 3
20 2 3
11 2 4
12 2 4
17 2 4