-2

I know I can use dplyr::select to rearrange columns, but, concretely, if I have a sequence of numeric columns/variables, is there a way to tell select or another function to rearrange these variables from that having maximum variance to that having minimum variance in a decreasing order?

This question could be also applied for other functions instead of variance, or other rules (which could also apply to character variables)...

iago
  • 2,990
  • 4
  • 21
  • 27

1 Answers1

1

Of course, just calculate the statistic for each column and use order.

xy <- data.frame(a = rnorm(10, mean = 5),
                 b = rnorm(10, mean = -3),
                 c = rnorm(10, mean = 4))

xy[, order(sapply(xy, FUN = mean))]

           b        c        a
1  -2.471796 2.425745 5.679503
2  -3.902212 4.954602 5.550362
3  -4.701174 4.319966 5.702840
4  -3.803088 3.187227 4.768257
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197