2015-11-30 137 views
4

我有一個相關矩陣,我試圖保持每對(行/列)的最大值(考慮絕對值)。我想問一下,如果我具有特定最大值的位置索引,如何提取值。值。 這是我的示例:在數據幀中選擇具有索引的列和行值

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

然後,我以最大價值的指標:這使我

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

LO3 Tx Gh RH SR 
2 5 4 5 4 

我現在想要的東西,它得到的這些位置的值爲每列。 這將是:

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

我試圖使用apply,但我不知道該怎麼做。或者如果還有其他方法可以做到這一點。

+3

只是'墊[cbind(1:nrow(mat),ind)]' –

回答

3

既然你有你的指數在ind一種方式可以是使用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 
+0

非常感謝,這是完美的! – user3231352

+0

非常歡迎@ user3231352。很高興我可以幫忙:) – LyzandeR

0

這能爲你做到這一點:

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

相關問題