Learn R Programming

psychTools (version 2.3.3)

dfOrder: Sort (order) a dataframe or matrix by multiple columns

Description

Although order will order a vector, and it is possible to order several columns of a data.frame by specifying each column individually in the call to order, dfOrder will order a dataframe or matrix by as many columns as desired. The default is to sort by columns in lexicographic order. If the object is a correlation matrix, then the selected columns are sorted by the (abs) max value across the columns (similar to fa.lookup in psych). If object is a correlation matrix, rows and columns are sorted.

Usage

dfOrder(object, columns,absolute=FALSE,ascending=TRUE)

Value

The original data frame is now in sorted order. If the input is a correlation matrix, the output is sorted by rows and columns.

Arguments

object

The data.frame or matrix to be sorted

columns

Column numbers or names to use for sorting. If positive, then they will be sorted in increasing order. If negative, then in decreasing order

absolute

If TRUE, then sort the absolute values

ascending

By default, order from smallest to largest.

Author

William Revelle

Details

This is just a simple helper function to reorder data.frames and correlation matrices. Originally developed to organize IRT output from the ltm package. It is a basic add on to the order function.

(Completely rewritten for version 1.8.1. and then again for 2.2.1 to allow sorting correlation matrices by numeric values.)

See Also

Other useful file manipulation functions include read.file to read in data from a file or read.clipboard from the clipboard, fileScan, filesList, filesInfo, and fileCreate

dfOrder code is used in the test.irt function to combine ltm and sim.irt output.

Examples

Run this code
#create a data frame and then sort it in lexicographic order
set.seed(42)
x <- matrix(sample(1:4,64,replace=TRUE),ncol=4)
dfOrder(x)  # sort by all columns
dfOrder(x,c(1,4))  #sort by the first and 4th column
x.df <- data.frame(x)
dfOrder(x.df,c(1,-2))  #sort by the first in increasing order, 
   #the second in decreasing order

#now show sorting correlation matrices  
r <- cor(sat.act,use="pairwise")
r.ord <- dfOrder(r,columns=c("education","ACT"),ascending=FALSE)
psych::corPlot(r.ord)

Run the code above in your browser using DataLab