Skip to content

Commit

Permalink
First pass at reorder
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Aug 8, 2016
1 parent 380c92e commit 9ee1bea
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@

export(fct_collapse)
export(fct_relevel)
export(fct_reorder)
importFrom(stats,median)
28 changes: 28 additions & 0 deletions R/reorder.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#' Reorder the levels of a function according to another variable
#'
#' \code{fct_reorder} is useful for 1d displays where the factor is mapped to
#' position; \code{fct_reorder2} for 2d displays where the factor is mapped to
#' a non-position aesthetic.
#'
#' \code{fct_reorder} is currently an almost exact copy of
#' \code{\link[stats]{reorder}} but it may change in the future.
#'
#' @param x A factor
#' @param y,fun fun The levels of \code{x} will be reordered so that \code{fun}
#' apply to each group is in ascending order.
#' @param ... Other arguments passed on to \code{fun}. A common argument is
#' \code{na.rm = TRUE}.
#' @importFrom stats median
#' @export
#' @examples
#' boxplot(Sepal.Width ~ Species, data = iris)
#' boxplot(Sepal.Width ~ fct_reorder(Species, Sepal.Width), data = iris)
fct_reorder <- function(x, y, fun = median, ...) {

summary <- tapply(y, x, fun, ...)
if (!is.numeric(summary) || length(summary) != nlevels(x)) {
stop("`fun` must return a single number per group", call. = FALSE)
}

factor(x, levels = levels(x)[order(summary)])
}
31 changes: 31 additions & 0 deletions man/fct_reorder.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9ee1bea

Please sign in to comment.