Is there an easier way to reorder data by column values?

I wrote this little wrapper around order , but I'm afraid my implementation is lame. I run into a corner, expecting the R command gods or algorithmic efficiency to hit my ergonomic keyboard: - (

 set.seed(1001) height <- rnorm(6, mean = 1, sd = 0.2) weight <- rnorm(6, mean = 100, sd = 15) id <- 1:6 dd <- data.frame(id, height, weight) # Here the function I came up with ReorderDataByColumn <- function(x, column) { ordered.indices <- order(x[ ,paste(column)]) return(x[ordered.indices, ]) } #And here are its results > ReorderDataByColumn(dd, column = "height") id height weight 4 4 0.4986928 76.09430 5 5 0.8885377 104.53967 3 3 0.9629449 86.38809 2 2 0.9644905 90.65584 6 6 0.9712881 124.51589 1 1 1.4377296 116.37253 > ReorderDataByColumn(dd, column = "weight") id height weight 4 4 0.4986928 76.09430 3 3 0.9629449 86.38809 2 2 0.9644905 90.65584 5 5 0.8885377 104.53967 1 1 1.4377296 116.37253 6 6 0.9712881 124.51589 
+4
source share
2 answers

I do not do amazing business on well-formulated questions. And I thought the code was readable and reasonable. If you want to tighten it up a bit, you can reset the paste () operation using "[[" and creating an index inside "[":

 ReorderDataByColumn2 <- function(x, column) { return(x[ order( x[[column]]), ]) } 

EDIT: adding a Hadley sentence (except, I think you also need do.call):

  ReorderDataByColumn2 <- function(x, column, desc=FALSE) { return( x[ do.call( order, x[ , column, drop=FALSE ] ), ] ) } 

You can add some errors if you want:

 ReorderDataByColumn2 <- function(x, column) { if(column %in% names(x)){return(x[ order( x[[column]]), ]) }else{ cat("Column ", column, "not in dataframe ", deparse(substitute(x))) } } 
+4
source

See the arrangement function in plyr:

 library(plyr) arrange(mtcars, cyl) arrange(mtcars, desc(cyl)) arrange(mtcars, vs, am) 

Function definition is pretty simple:

 arrange <- function (df, ...) { ord <- eval(substitute(order(...)), df, parent.frame()) unrowname(df[ord, ]) } 

And it works with a very similar process to subset in R.

+2
source

All Articles