I'm trying to transform the values in a matrix by dividing each value by the lesser of the maximum values of its column or row name. I am having trouble because I don't know how to query the row/column for a particular value from inside a larger function.
A small cut of the data looks like this: a weighted (symmetrical) adjacency matrix, mat:
Acousmatic Acoustic Afro-beat Alternative Ambient
Acousmatic 125 11 3 3 1
Acoustic 11 112398 1810 24216 3824
Afro-beat 3 1810 10386 1220 298
Alternative 3 24216 1220 103286 2838
Ambient 1 3824 298 2838 20400
As an example, I want to transform the value of "Alternative-Acoustic" (24216) by finding the maximum value for "Acoustic" given by its diagonal (112398) and the maximum value for "Alternative" given by its diagonal (103286), and by dividing "Alternative-Acoustic" (24216) by the lesser of those two numbers. So in this case, the lesser would be "Alternative," so I want to transform the "Alternative-Acoustic" value with 24216/103286=~.2345.
I want to automatically perform this transformation for all values in this matrix, which would result in a matrix with values ranging from 0-1 with the diagonals as all 1's.
I tried the following in many different iterations with "mat" as both a matrix and a data frame, but I do not know how to correctly query the row and column maximums for each value in the matrix. This is using nonexistent functions ('colmax' and 'rowmax'), but I think it most clearly expresses what I want to do:
transformedmat <- apply(mat,1:2, function(x) x/min(colmax(x),rowmax(x)))
I also tried to write an embedded function, but that ended poorly, and I'm wondering if there's a simpler solution:
rescalemat <- function(mat){
apply(mat, 1, function(x){
colmax<-apply(mat, 2, function(x) max(x))
rowmax<-apply(mat, 1, function(x) max(x))
x/min(colmax,rowmax)
mat
})
}
Any help would be greatly appreciated.
Thanks.