1

My data set is :

S1   S2   S3    S4 
1    4    7     20
2    6    8     21
3    9    10    30

and i convert data as per condition that sort as per maximum difference value between each column value

data after the condition should be like this

S4    S2    S3    S1 
20    4     7     1
21    6     8     2
30    9     1     3

explanation: the difference between max and min value

for S4 is 30 - 20 =10

for S2 is 9-4 = 5

for S3 is 10-7 = 3

for S1 is 3-1 =2

and the columns are sorted as per the difference value of max and min.

  • Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Sep 06 '17 at 13:46

3 Answers3

2

Here is an idea via base R,

df[order(sapply(df, function(i) max(i)-min(i)), decreasing = TRUE)]

which gives,

  S4 S2 S3 S1
1 20  4  7  1
2 21  6  8  2
3 30  9 10  3

If you want to change the column names to reflect the order you can use setNames, i.e.

setNames(df[order(sapply(df, function(i) max(i)-min(i)), decreasing = TRUE)], 
         paste0('column', seq_along(df))) 

which gives,

   column1 column2 column3 column4
1      20       4       7       1
2      21       6       8       2
3      30       9      10       3
Sotos
  • 51,121
  • 6
  • 32
  • 66
1

Here is an option using tidyverse

library(tidyverse)
df1 %>% 
   summarise_all(funs(max(.)-min(.))) %>%
   unlist %>% 
   order(., decreasing = TRUE) %>% 
   select(df1, .)
#  S4 S2 S3 S1
#1 20  4  7  1
#2 21  6  8  2
#3 30  9 10  3
akrun
  • 874,273
  • 37
  • 540
  • 662
0
 df1[,order(sapply(df1,function(x)diff(range(x))),decreasing = T)]
   S4 S2 S3 S1
 1 20  4  7  1
 2 21  6  8  2
 3 30  9 10  3
Onyambu
  • 67,392
  • 3
  • 24
  • 53