2
votes

For a dataframe similar to the one below (but with more variables), I want to reorder the columns based on the descending sum of the variables. So in my example the column order should be VAR3 (sum=7), VAR2 (sum=5), VAR1 (sum=4). I know I can do it manually but my actual dataframe has too many variables.

dat <- data.frame(VAR1=c(0,1,0,1,0,0,1,1,0),
           VAR2=c(1,1,0,1,0,0,1,0,1), 
           VAR3=c(0,1,1,1,1,0,1,1,1))

  VAR1 VAR2 VAR3
1    0    1    0
2    1    1    1
3    0    0    1
4    1    1    1
5    0    0    1
6    0    0    0
7    1    1    1
8    1    0    1
9    0    1    1
2

2 Answers

3
votes
dat <- data.frame(VAR1=c(0,1,0,1,0,0,1,1,0),
              VAR2=c(1,1,0,1,0,0,1,0,1), 
              VAR3=c(0,1,1,1,1,0,1,1,1))


dat1 <- dat[,names(sort(colSums(dat), decreasing = TRUE))]

dat1
   VAR3 VAR2 VAR1
1    0    1    0
2    1    1    1
3    1    0    0
4    1    1    1
5    1    0    0
6    0    0    0
7    1    1    1
8    1    0    1
9    1    1    0
1
votes
dat[,names(sort(colSums(dat), decreasing = T))]

colSums gives sums of all columns of the dat

> colSums(dat)

VAR1 VAR2 VAR3 
 4    5    7 

sort it in a decreasing order of sum value

> sort(colSums(dat), decreasing = T)

VAR3 VAR2 VAR1 
7    5    4 

Get the names in this exact order and display dat columns in the same order

> dat[,names(sort(colSums(dat), decreasing = T))]

    VAR3 VAR2 VAR1
1    0    1    0
2    1    1    1
3    1    0    0
4    1    1    1
5    1    0    0
6    0    0    0
7    1    1    1
8    1    0    1
9    1    1    0