按第n列排序数据,获取第一行的rowname,为每列执行此操作

时间:2016-10-25 07:20:54

标签: r loops append

使用此数据框

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. 订购数据
  3. 取第一行的rowname并将其附加到空矢量
  4. 对Dim.2重复此操作:Dim5将第一个rowname附加到同一个矢量。
  5. 我试过了:

    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)是空的。

2 个答案:

答案 0 :(得分:2)

使用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"

答案 1 :(得分:1)

选项为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"