簡體   English   中英

提取行和列的最大值

[英]Extract the max values for row and column

我需要查找行最大和列最大用於相同位置的值。 測試數據(實際數據不必是方矩陣):

scores<-structure(c(0.4, 0.6, 0.222222222222222, 0.4, 0.4, 0, 0.25, 0.5, 
0.285714285714286), .Dim = c(3L, 3L), .Dimnames = list(c("a", 
"b", "c"), c("d", "e", "f")))

我已經發現哪些列/行具有該行/列的最大值。

rows<-structure(list(a = c("d", "e"), b = "d", c = "f"), .Names = c("a", 
"b", "c"))
cols<-structure(list(d = "b", e = c("a", "b"), f = "b"), .Names = c("d", 
"e", "f"))

但是我無法從矩陣中獲取值。 問題是當相同的(最大值)值出現兩次或兩次以上。 我不知道如何檢查該案件的索引。 我嘗試使用mapply:

mapply(function(x, y) {
    cols[x] == rows[y] 
    }, rows, cols)

但這在行或列具有多個元素時停止。

預期輸出: c(0.6, 0.4)
第一個是第1列和第2列的最大值,第二個是第1行和第2列的最大值。

            d   e         f   | Max
a   0.4000000 0.4 0.2500000   0.4
b   0.6000000 0.4 0.5000000   0.6
c   0.2222222 0.0 0.2857143   0.2857
Max:  0.6     0.4 0.5

如您所見,第2行和第1列的最大值相同,而第1行和第1列的最大值相同,但第3行和第3列的最大值不同

我想,我了解您正在嘗試做的事情。 雖然不是最佳解決方案。

我們找出行和列中最大值的索引,然后找出與數據框intersect並顯示相應值的索引。

a1 <- which(apply(scores, 1, function(x) x == max(x)))
a2 <- which(apply(scores, 2, function(x) x == max(x)))
scores[intersect(a1, a2)]

#[1] 0.6 0.4

並在一行中

scores[intersect(which(apply(scores, 1, function(x) x == max(x))), 
                 which(apply(scores, 2, function(x) x == max(x))))]

這就是你想要的:

# Compute rows and columns max and rows max positions
row_max<-apply(scores, 1, max)
row_max_pos<-apply(scores, 1, which.max)
col_max<-apply(scores, 2, max)

# For each row, check if max is equal to corresponding column max
res <- sapply(1:length(row_max), 
              function(i) ifelse(row_max[i] == col_max[row_max_pos[i]], T, F))
row_max[res]

它還可以在多個行/列上使用相同的最大值,例如使用以下數據:

scores <- structure(c(0.4, 0.6, 0.222222222222222, 0.4, 0.4, 0, 0.25, 0.5, 
                      0.285714285714286, 0.13, 0.2, 0.6), .Dim = c(4L, 3L), 
                      .Dimnames = list(c("a", "b", "c", "d"), c("e", "f", "g")))

暫無
暫無

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

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