Use the order()
function.
An exemplary data frame:
df <- data.frame(s1=runif(5), s2=runif(5), s3=runif(5))
df[1,2] <- NA # some NAs
df
## s1 s2 s3
## 1 0.74473576 NA 0.71547379
## 2 0.66997782 0.6474405 0.62320795
## 3 0.05361586 0.5370381 0.03298139
## 4 0.06209263 0.9409920 0.46096984
## 5 0.42432948 0.9983042 0.38503196
Calculate column means, with NAs omitted:
(mns <- colMeans(df, na.rm=TRUE))
## s1 s2 s3
## 0.3909503 0.7809437 0.4435330
The desired column ordering is:
order(mns)
## [1] 1 3 2
(s1
goes first, s2
goes last, and s3
should become the 2nd column)
Now you may reorder the columns:
(df <- df[,order(mns)])
## s1 s3 s2
## 1 0.74473576 0.71547379 NA
## 2 0.66997782 0.62320795 0.6474405
## 3 0.05361586 0.03298139 0.5370381
## 4 0.06209263 0.46096984 0.9409920
## 5 0.42432948 0.38503196 0.9983042