| reorder.factor {gregmisc} | R Documentation |
Reorder the levels of a factor
## S3 method for class 'factor': reorder(x, order, ...)
x |
factor. |
order |
Vector of indexes or label names for new factor ordering. |
... |
Optional parameters (ignored.) |
When order is a numeric vector, this function is simply a
convenence wrapper for factor(x,levels=levels(x)[order]).
Otherwise this functionis simply a wrapper for
factor(x,levels=order).
I find this function useful for reordering factors so that the default treatment contrasts use the appropriate levels for comparison.
A new factor with the levels ordered as specified. Note that levels
not specified order will become missing values.
Gregory R. Warnes Gregory_R_Warnes@groton.pfizer.com
# Create a 4 level example factor
trt <- factor( sample( c("PLACEBO","300 MG", "600 MG", "1200 MG"),
100, replace=TRUE ) )
summary(trt)
# Note that the levels are not in a meaningful order.
# Change the order to something useful
# using indexes:
trt2 <- reorder(trt, c(4,2,3,1))
summary(trt2)
# using label names:
trt2 <- reorder(trt, c("PLACEBO","300 MG", "600 MG", "1200 MG") )
summary(trt2)
# drop out the '300 MG' level
trt3 <- reorder(trt, c("PLACEBO", "600 MG", "1200 MG") )
summary(trt3)