Order the data by nth column, get rowname of first

2019-08-03 05:27发布

问题:

Using this dataframe

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

My intention is to:

  1. Order the data by Dim.1
  2. Take the rowname of first row and append it to an empty vector
  3. Repeat this for Dim.2:Dim5 appending the first rowname to the same vector.

I tried this:

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))
  }

But the vector (clim_var) is empty.

回答1:

Using which.min and sapply:

# 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"


回答2:

An option is 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"


标签: r loops append