Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder columns in a 'canonical' way after mutate_each or summarise_each

Take the following example.

library(dplyr)
temp <- data.frame(lapply(1:3, function(i) rnorm(5, 0, 1)))
names(temp) <- paste0("X", 1:3)

temp_each <-
    temp %>%
    mutate_each(funs(mean, median))

Examining the names of temp_each, we see that

> names(temp_each)
[1] "X1"        "X2"        "X3"        "X1_mean"   "X2_mean"   "X3_mean"   "X1_median" "X2_median" "X3_median"

that is, the final columns are in groups of three, always ordered X1, X2, X3 + the function applied.

However, I would like it to look like this

[1] "X1"        "X1_mean"   "X1_median" "X2"        "X2_mean"   "X2_median" "X3"        "X3_mean"   "X3_median"

Does anyone know how to implement this, preferably using dplyr, for a data frame with many many columns and arbitrary column names?

like image 430
Alex Avatar asked Feb 10 '23 17:02

Alex


1 Answers

Here you could use mixedorder from gtools

library(gtools)
temp_each[,mixedorder(colnames(temp_each))]

#           X1    X1_mean  X1_median         X2    X2_mean  X2_median
#1  0.28285115 -0.4369067 0.08556155 -0.9402162 -0.9857593 -0.7676634
#2 -1.29193398 -0.4369067 0.08556155 -0.5442052 -0.9857593 -0.7676634
#3 -1.42261044 -0.4369067 0.08556155 -0.7676634 -0.9857593 -0.7676634
#4  0.16159810 -0.4369067 0.08556155 -2.2270920 -0.9857593 -0.7676634
#5  0.08556155 -0.4369067 0.08556155 -0.4496198 -0.9857593 -0.7676634
#           X3   X3_mean   X3_median
#1  0.04606554 0.0923336 -0.08168136
#2 -0.08168136 0.0923336 -0.08168136
#3  0.90535333 0.0923336 -0.08168136
#4 -0.15699052 0.0923336 -0.08168136
#5 -0.25107897 0.0923336 -0.08168136
like image 192
Veerendra Gadekar Avatar answered Feb 12 '23 06:02

Veerendra Gadekar