简体   繁体   中英

Extract the max values for row and column

I need to fin the values for which the row max and the column max are for the same position. Test data (The real data doesn't need to be a square matrix):

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")))

I already found which are the columns/rows with the max value for that row/column.

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"))

But I don't manage to get the values from the matrix. The problem are when the same (max) value appear twice or more. I don't know how to check the indices of that case. I tried using mapply:

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

But this stops when rows or cols has more than one element.

Expected output: c(0.6, 0.4)
The first is the max value of column 1 and row 2, the second value is the max value of row 1 and column 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

As you can see for row 2 and column 1 the max value is the same, and for row 1 and column 1 it is the same value, but for row 3 and column 3 it isn't

I think , I understood what you are trying to do. Not an optimal solution though.

We find out the indices for maximum value in rows as well as column and then find out the indices which intersect and display the corresponding value from the dataframe.

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

And in one-line

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

This is what you want:

# 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]

It also work with same max values on multiple rows/columns, for example with this data:

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")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM