簡體   English   中英

在行中查找第二個最大值並將其名稱粘貼到R中的列中

[英]Find second maximum value in a row and paste its name in a column in R

我有一個看起來像這樣的概率數據集

       topic_1      topic_2     topic_3      topic_4      topic_5      topic_6 most_probable
1 0.0028043479 0.0035351980 0.979083973 0.0045751502 0.0046371627 0.0053641679       topic_3
2 0.9688616242 0.0035351980 0.013026697 0.0045751502 0.0046371627 0.0053641679       topic_1
3 0.9928927297 0.0008069017 0.002973317 0.0010442686 0.0010584229 0.0012243603       topic_1
4 0.9841620200 0.0017981155 0.006625797 0.0023270686 0.0023586102 0.0027283884       topic_1
5 0.0004441958 0.0005599591 0.002063369 0.0007246827 0.9953581342 0.0008496595       topic_5

我使用此函數找到了最可能的值

documents.topics$most_probable <- unlist(
lapply(
  1:nrow(documents.topics),
  function(x){
  names(which.max(documents.topics[x,]))}))
documents.topics$most_probable <- as.factor(documents.topics$most_probable)

我想知道如何找到第二個最大值並將其名稱粘貼到新列second_probable

我們可以使用applysortwhich功能:

dat$second_most_probable <- apply(dat[,-7], 1, 
FUN = function(x) which(x == sort(x, decreasing = TRUE)[2]))

對於每一行,我們sort以遞減順序的數據,並且然后從向量的第二元件。 然后,我們發現which列中的第二大元素相匹配。 我們使用的結果which確定列名。

數據

dat <- structure(list(topic_1 = c(0.0028043479, 0.9688616242, 0.9928927297, 
0.98416202, 0.0004441958), topic_2 = c(0.003535198, 0.003535198, 
0.0008069017, 0.0017981155, 0.0005599591), topic_3 = c(0.979083973, 
0.013026697, 0.002973317, 0.006625797, 0.002063369), topic_4 = c(0.0045751502, 
0.0045751502, 0.0010442686, 0.0023270686, 0.0007246827), topic_5 = c(0.0046371627, 
0.0046371627, 0.0010584229, 0.0023586102, 0.9953581342), topic_6 = c(0.0053641679, 
0.0053641679, 0.0012243603, 0.0027283884, 0.0008496595), most_probable = c("topic_3", 
"topic_1", "topic_1", "topic_1", "topic_5")), .Names = c("topic_1", 
"topic_2", "topic_3", "topic_4", "topic_5", "topic_6", "most_probable"
), class = "data.frame", row.names = c("1", "2", "3", "4", "5"
))

這是max.col另一個選項。 我們基於“ most_probable”列名稱將數據集中的值提取到數據集副本中的-Inf 然后使用max.col獲取最大值列的索引,並使用該索引獲取列名

dat1 <- dat
dat1[cbind(1:nrow(dat), match( dat$most_probable, names(dat)))] <- -Inf
dat$second_most_probable <- names(dat)[max.col(dat1[-7])]
dat$second_most_probable
#[1] "topic_6" "topic_3" "topic_3" "topic_3" "topic_3"

暫無
暫無

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

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