Select column and row values โ€‹โ€‹with index in data frame

I have a correlation matrix, and I'm trying to keep the maximum value (given the absolute values) of each pair (row / column). I wanted to ask how to extract values โ€‹โ€‹if I have a position index with a specific max. cost. This is my example:

mat <- structure(c(0, 0.428291512801413, 0.124436112431533,    -0.345870125921382, 
             0.391613957773281, 0.428291512801413, 0, 0.341415068127906, -0.346724601510298, 
             0.486360835614514, 0.124436112431533, 0.341415068127906, 0, -0.496213980990412, 
             0.41819049956841, -0.345870125921382, -0.346724601510298, -0.496213980990412, 
             0, -0.80231408836218, 0.391613957773281, 0.486360835614514, 0.41819049956841, 
            -0.80231408836218, 0), .Dim = c(5L, 5L), .Dimnames = list(c("LO3","Tx", "Gh", "RH", "SR"), c("LO3", "Tx", "Gh", "RH", "SR"))) 

Then I take the index of the maximum value:

ind <- apply(abs(mat), 2, which.max) 

which gives me:

LO3  Tx  Gh  RH  SR 
2   5   4   5   4

What I wanted now was getting the value of this position for each column. which will be:

LO3       Tx        Gh
0.4282915 0.4863608  -0.4962140 .....

I tried to use it apply, but I donโ€™t know how to do it .. or if there was another way to do it.

+4
source share
2 answers

Since you have indexes in ind, one way might be to use mapply:

#the first argument is the function call 
#second argument is your matrix coerced to data.frame
#third argument is your indices
#each time an index will be used in conjunction to a column
#and you get your result
mapply(function(x,y) x[y], as.data.frame(mat), ind)
#       LO3         Tx         Gh         RH         SR 
# 0.4282915  0.4863608 -0.4962140 -0.8023141 -0.8023141 
+3

:

mapply(function(i,j) sample[i,j], seq_len(ncol(sample)), ind)

> mapply(function(i,j) sample[i,j], seq_len(ncol(sample)), ind)
[1]  0.4282915  0.4863608 -0.4962140 -0.8023141 -0.8023141

, ind

0

Source: https://habr.com/ru/post/1617965/


All Articles