本文介绍了按第n列排序数据,获取第一行的行名,对每一列执行此操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用此数据框
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
我的意图是
- 按Dim.1排序数据
- 采用第一行的行名并将其附加到空向量
- 对于Dim.2:Dim5重复此操作,将第一个行名附加到相同的向量上.
我尝试过:
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)是空的.
But the vector (clim_var) is empty.
推荐答案
使用which.min
和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"
这篇关于按第n列排序数据,获取第一行的行名,对每一列执行此操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!