[R] Howto sort dataframe columns by colMeans

jim holtman jholtman at gmail.com
Tue Sep 4 22:33:39 CEST 2007


Here is one way of doing it by 'skipping' the first column which is a
factor and your 'time':

> x <- read.table(textConnection(" time   met-a    met-b    met-c
+ 00:00    42         18          99
+ 00:05    88         16          67
+ 00:10    80         27          84"), header=TRUE)
> x.mean <- colMeans(x[-1])
> x.new <- x[,c('time', names(sort(x.mean, decreasing=TRUE)))]
>
> x.new
   time met.c met.a met.b
1 00:00    99    42    18
2 00:05    67    88    16
3 00:10    84    80    27
>


On 9/4/07, Lynn Osburn <lynn.osburn at lewan.com> wrote:
>
> I read from external data source containing several columns.  Each column
> represents value of a metric.  The columns are time series data.
>
> I want to sort the resulting dataframe such that the column with the largest
> mean is the leftmost column, descending in colMean values to the right.
>
> I see many solutions for sorting rows based on some column characteristic,
> but haven't found any discussion of sorting columns based on column
> characteristics.
>
> viz.  input data looks like this
>  time   met-a    met-b    met-c
> 00:00    42         18          99
> 00:05    88         16          67
> 00:10    80         27          84
>
> desired output:
>  time   met-c    met-a     met-b
> 00:00    99         42          18
> 00:05    67         88          16
> 00:10    84         80          27
>
> Thanks,
> -Lynn
>
> --
> View this message in context: http://www.nabble.com/Howto-sort-dataframe-columns-by-colMeans-tf4380044.html#a12485729
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list