Skip to content

Instantly share code, notes, and snippets.

@alexland
Created October 10, 2012 02:13
Show Gist options
  • Save alexland/3862756 to your computer and use it in GitHub Desktop.
Save alexland/3862756 to your computer and use it in GitHub Desktop.
sorting a data frame on a numeric variable conditioned on a factor variable
DF1 = DF[order(DF$factor_var, -xtfrm(DF$numeric_var)),]
DF1$idx = sequence(rle(as.character(DF1$factor_var))$lengths)
$> # e.g., sort a data frame based on 'price' (numeric variable)
$> # 'grouped by' the levels of 'color' (factor, or discrete variable)
$> data(diamonds, package="ggplot2")
$> DF = diamonds[1:1000,] # first thousand rows of DF
$> DF1 = DF[order(DF$color, -xtfrm(DF$price)),]
$> DF1$idx = sequence(rle(as.character(DF1$color))$lengths)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment