根据平均值重新排序R数据帧中的列

use*_*668 3 average r

我想根据每列的算术平均值对数据框的列重新排序.

对于:

S1 S2 S3
1  1  1
2  1  1
3  3  1 
Run Code Online (Sandbox Code Playgroud)

预期的产出是:

S3 S2 S1
1  1  1 
1  1  2 
1  3  3 
Run Code Online (Sandbox Code Playgroud)

在上述情况下,平均值分别为:S1 = 2,S2 = 1.6666S3 = 1,反相S1和S3列位置中的数据帧.

另外,我的真实数据也有NA的值.

gag*_*ews 7

使用该order()功能.

示例性数据框:

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
Run Code Online (Sandbox Code Playgroud)

计算列平均值,省略NA:

(mns <- colMeans(df, na.rm=TRUE))
##        s1        s2        s3 
## 0.3909503 0.7809437 0.4435330 
Run Code Online (Sandbox Code Playgroud)

所需的列顺序是:

order(mns)
## [1] 1 3 2
Run Code Online (Sandbox Code Playgroud)

(s1先行,s2最后,s3应该成为第二列)

现在您可以重新排序列:

(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
Run Code Online (Sandbox Code Playgroud)