订购由n列的数据,获得第一排的rowname,为每列做(Order the data by nth

2019-09-28 02:22发布

使用这个数据帧

head(pcaFM_clim_var_cos2[,1:5])

                     Dim.1      Dim.2     Dim.3        Dim.4      Dim.5
dtr_mean_value_1 0.2583860 0.04524243 0.3004670 4.714854e-02 0.05262342
dtr_mean_value_2 0.2470183 0.04818929 0.3380621 4.220726e-02 0.05577386
dtr_mean_value_3 0.2459333 0.07231365 0.3690537 9.016624e-03 0.08165524
dtr_mean_value_4 0.2740264 0.09818961 0.3053862 2.670571e-03 0.08860495
dtr_mean_value_5 0.1910882 0.18521379 0.3373460 7.113687e-06 0.07396737
dtr_mean_value_6 0.2109406 0.18532406 0.3185838 6.542807e-03 0.10550687

我的目的是:

  1. 订购由Dim.1数据
  2. 以第一行的rowname并追加到一个空载体
  3. 重复此Dim.2:Dim5追加第一rowname相同的载体。

我尝试这样做:

a <- character()
for (i in 1:5){
pcaFM_clim_var_cos2[order(-pcaFM_clim_var_cos2[,i])]
  clim_var <- append(a,head(pcaFM_clim_var_cos2[,0],1))
  }

但是,向量(clim_var)是空的。

Answer 1:

使用which.minsapply

# data
pcaFM_clim_var_cos2 <- read.table(text = "
Dim.1      Dim.2     Dim.3        Dim.4      Dim.5
dtr_mean_value_1 0.2583860 0.04524243 0.3004670 4.714854e-02 0.05262342
dtr_mean_value_2 0.2470183 0.04818929 0.3380621 4.220726e-02 0.05577386
dtr_mean_value_3 0.2459333 0.07231365 0.3690537 9.016624e-03 0.08165524
dtr_mean_value_4 0.2740264 0.09818961 0.3053862 2.670571e-03 0.08860495
dtr_mean_value_5 0.1910882 0.18521379 0.3373460 7.113687e-06 0.07396737
dtr_mean_value_6 0.2109406 0.18532406 0.3185838 6.542807e-03 0.10550687",
                                  header = TRUE)

# using which.min
clim_var <- 
  row.names(pcaFM_clim_var_cos2)[sapply(pcaFM_clim_var_cos2, which.min)]

clim_var
# [1] "dtr_mean_value_5" "dtr_mean_value_1" "dtr_mean_value_1" "dtr_mean_value_5" "dtr_mean_value_1"


Answer 2:

一种选择是max.col

row.names(pcaFM_clim_var_cos2)[max.col(-t(pcaFM_clim_var_cos2))]
#[1] "dtr_mean_value_5" "dtr_mean_value_1" "dtr_mean_value_1" 
#[4] "dtr_mean_value_5" "dtr_mean_value_1"


文章来源: Order the data by nth column, get rowname of first row, do this for each column
标签: r loops append