我的代碼如下。它在最小值所在的行和列名稱中查找最小值。我如何修改我的代碼以獲取第2,3,4,5個最小值和各個列名的值?r在數據框的行中找到第二個最小值並獲取列索引
x = t(data.frame(c(11,12,1,14,15)))
colnames(x)=c('a','b','c','d','e')
minimum = apply(x, 1, min)
minimum
index = colnames(x)[apply(x, 1, which.min)]
index
------------------------------- UPDATE1
我嘗試下面的代碼。 myans_a有5列。但是代碼失敗
#function to find second minimum and associated class name
min <- function(x,n) {
value = sort(x, FALSE)[n]
column_name = colnames(x)[which(x == value, arr.ind = TRUE)[2]]
paste0("Column:",column_name," , Value:",value)
}
myans_a=myans[,c(1:5)]
min(myans_a,3)
> min(myans_a,3)
Show Traceback
Rerun with Debug
Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) :
undefined columns selected
試着用'sort'即'申請(X,1,函數(x)的名稱(排序(X)[2]))' – akrun
看一看[1 ](http://stackoverflow.com/questions/2453326/fastest-way-to-find-second-third-highest-lowest-value-in-vector-or-column)&[2](http:// stackoverflow .com/questions/5569038 /最快速的方式找到索引的第二個第三高的最低價值) – user2100721