Learn R Programming

collapse (version 1.7.5)

colorder: Fast Reordering of Data Frame Columns

Description

Efficiently reorder columns in a data frame (no copies). To do this by reference see also data.table::setcolorder.

Usage

colorder(X, …, pos = "front")

colorderv(X, neworder = radixorder(names(X)), pos = "front", regex = FALSE, …)

Arguments

X

a data frame or list.

for colorder: Column names of X in the new order (can also use sequences i.e. col1:coln, newname = colk, …). For colorderv: Further arguments to grep if regex = TRUE.

neworder

a vector of column names, positive indices, a suitable logical vector, a function such as is.numeric, or a vector of regular expressions matching column names (if regex = TRUE).

pos

integer or character. Different options regarding column arrangement if ...length() < ncol(X) (or length(neworder) < ncol(X)).

Int. String Description
1 "front" move specified columns to the front of X (the default).
2 "end" move specified columns to the end of X.
3 "exchange" just exchange the positions of selected columns in X, other columns remain in the same position.
4 "after" place all further selected columns behind the first selected column.
regex

logical. TRUE will do regular expression search on the column names of X using a (vector of) regular expression(s) passed to neworder. Matching is done using grep. Note that multiple regular expressions will be matched in the order they are passed, and funique will be applied to the resulting set of indices.

Value

X with columns re-ordered (no deep copy).

See Also

roworder, Data Frame Manipulation, Collapse Overview

Examples

Run this code
# NOT RUN {
head(colorder(mtcars, vs, cyl:hp, am))
head(colorder(mtcars, vs, cyl:hp, am, pos = "end"))
head(colorder(mtcars, vs, cyl:hp, am, pos = "after"))
head(colorder(mtcars, vs, cyl, pos = "exchange"))
head(colorder(mtcars, vs, cyl:hp, new = am))    # renaming

## Same in standard evaluation
head(colorderv(mtcars, c(8, 2:4, 9)))
head(colorderv(mtcars, c(8, 2:4, 9), pos = "end"))
head(colorderv(mtcars, c(8, 2:4, 9), pos = "after"))
head(colorderv(mtcars, c(8, 2), pos = "exchange"))
# }

Run the code above in your browser using DataLab