考虑我有一个df
> editor
A B C D E F G H I J
User1 1 0 5 6 5 6 5 6 2 6
User2 0 5 4 6 4 5 5 1 7 5
Run Code Online (Sandbox Code Playgroud)
我想在上面的行中存储第一个出现的第二大值的列名.预期成绩
> editor
A B C D E F G H I J 2nd_highest
User1 1 0 5 6 5 6 5 6 2 6 C
User2 0 5 4 6 4 5 5 1 7 5 D
Run Code Online (Sandbox Code Playgroud)
我试过,edited$2nd_highest <- colnames(edited)[apply(edited, 1, which.max)+1]但没有运作良好.
有任何想法吗 ?
这是尝试使用代数来实现这一点,以便保持矢量化并避免行操作(尽管它仍然进行类似的矩阵转换apply).这里的想法是找到最大值 - 然后从数据集中减少它,然后转换为log(在乘以-1之后),这将导致最大值变为-Inf(意味着最小值)然后1/result为了找到最大值超出剩余价值的价值.
indx <- max.col(1/log((editor - editor[cbind(1:nrow(editor),
max.col(editor))]) * -1), ties.method = "first")
names(editor)[indx]
# [1] "C" "D"
Run Code Online (Sandbox Code Playgroud)