簡體   English   中英

使用colnames和apply返回數據框行中第一個出現的第二大值

[英]Return first occurring 2nd largest value in data frame rows using colnames & apply

考慮我有一個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

我想在上面的行中存儲第一個出現的第二大值的列名。 預期成績

> 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

我嘗試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"

這是一個想法。 我們首先對每行的unique值進行排序並提取第二個值。 由於我們指定decreasing = TRUE ,因此第二個值將是第二個最高值。 然后,我們使用新列表的每個元素的第一個值作為列名的索引

ind_lst <- apply(df, 1, function(i) which(i == sort(unique(i), decreasing = TRUE)[2]))
df$highest.two <- names(df)[unlist(lapply(ind_lst, '[', 1))]
df
#      A B C D E F G H I J highest.two
#User1 1 0 5 6 5 6 5 6 2 6           C
#User2 0 5 4 6 4 5 5 1 7 5           D

這可以幫助您:

mat <- matrix(sample(1:8, 24, replace=TRUE), ncol=6)
mat
sec_highest <- apply(mat, 1, function(x) which(x == max(x[which(x != max(x))])))
LETTERS[sec_highest] # letters display

請注意,如果您有兩個具有相同分數的第二個高分,則只會顯示一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM