which.max() 提取最后一个最大值

which.max() to extract the last largest value

在我的代码中,我想提取一系列列中的最后一个最大值,逐行遍历数据框。问题是我的脚本只给我第一次出现(在本例中是第一列的名称)的最大值。关于如何更新此行以获得最后最大值的任何建议?

我的数据框如下所示:

A.trust B.trust C.trust D.trust E.trust F.trust G.trust H.trust I.trust J.trust K.trust L.trust M.trust
-999    -999    -999    -999    -999    -999    -999.0  -999.0  -999.0   -999   -999    -999    -999
-999    -999    -999    -999    -999    -999     0.5    -999.0   0.5     -999   -999    -999    -999
-999    -999    -999    -999    -999    -999    -999.0  -999.0   1.0     -999   -999    -999    -999
-999    -999    -999    -999    -999    -999    -999.0  -999.0  -999.0   -999   -999    -999    -999
-999    -999    -999    -999    -999    -999    -999.0  -999.0  -999.0   -999   -999    -999    -999
-999    -999    -999    -999    -999    -999     0.5     0.5    -999.0   -999   -999    -999    -999

我正在使用以下代码

# return cols which hold maximum
nams <- names(test)[apply(test, 1 ,which.max)]

当前输出

目前,nams变量中的值为:

"A.trust"
"G.trust" 
"I.trust" 
"A.trust"
"A.trust" 
"G.trust"

需要输出

我在 nams 变量中的要求值是这样的:

"M.trust" 
"I.trust" 
"I.trust"
"M.trust" 
"M.trust" 
"H.trust"

dput()

test = structure(list(A.trust = c(-999, -999, -999, -999, -999, -999), 
               B.trust = c(-999, -999, -999, -999, -999, -999), 
               C.trust = c(-999, -999, -999, -999, -999, -999), 
               D.trust = c(-999, -999, -999, -999, -999, -999), 
               E.trust = c(-999, -999, -999, -999, -999, -999), 
               F.trust = c(-999, -999, -999, -999, -999, -999), 
               G.trust = c(-999,  0.5, -999, -999, -999,  0.5), 
               H.trust = c(-999, -999, -999, -999, -999,  0.5), 
               I.trust = c(-999,  0.5,  1,   -999, -999, -999), 
               J.trust = c(-999, -999, -999, -999, -999, -999), 
               K.trust = c(-999, -999, -999, -999, -999, -999), 
               L.trust = c(-999, -999, -999, -999, -999, -999), 
               M.trust = c(-999, -999, -999, -999, -999, -999)), 
          row.names = 600:605, class = "data.frame")

相关帖子

以下 post 与我的问题相关,但我正在努力解决如何在我的脚本中进行此更改 . This is another related post which.max ties method in R。 任何帮助将不胜感激!

names(rev(test))[apply(rev(test), 1, which.max)]
[1] "M.trust" "I.trust" "I.trust" "M.trust" "M.trust" "H.trust"

另一种可能性(可能效率低于@Skaqqs 的回答):

names(test)[apply(test, 1, function(x) tail(which(x == max(x)), 1)]

我们可以使用矢量化选项

 names(test)[ncol(test):1][max.col(rev(test), "first")]
[1] "M.trust" "I.trust" "I.trust" "M.trust" "M.trust" "H.trust"