2013-07-22 109 views
1

給定一個矩陣,用最大值提取列的行名稱是一個常見問題。從R中的矩陣中提取最大值(隨機選擇)

sapply(mat,2,which.max) 

mat<-matrix(list(20,0,0,80,80,0, 
       20,0,40,0,40,20, 
       40,0,40,20,20,0, 
       0,80,40,20,20,20),ncol=6,byrow=T) 
rownames(mat)<-c("A","C","G","T") 

但在這裏,一些列具有兩個相似的最大值(在該示例矩陣,列3和4)。默認情況下,腳本選擇「A」在第3列和第4列中具有最大列值的行。我在編寫腳本時在隨機選擇兩個行名稱(A和T)中遇到麻煩,和4. 任何有關腳本的幫助表示讚賞。

回答

3

rank功能就派上用場了:

> apply(mat,2,function(x) which(rank(-unlist(x), ties.method="random") == 1)) 
[1] 3 4 4 1 1 2 
> apply(mat,2,function(x) which(rank(-unlist(x), ties.method="random") == 1)) 
[1] 3 4 3 1 1 2 
> apply(mat,2,function(x) which(rank(-unlist(x), ties.method="random") == 1)) 
[1] 3 4 4 1 1 4 

ties.method="random"部分是解決以隨機方式的關係是至關重要的。

+0

+1我之前沒有理由使用rank函數。可以派上用場,謝謝! –

2

考慮閱讀documentation for which.max,建議使用which.is.maxnnet。要麼借用該算法,要麼使用該包。

> library(nnet) 
> which.is.max 
function (x) 
{ 
    y <- seq_along(x)[x == max(x)] 
    if (length(y) > 1L) 
     sample(y, 1L) 
    else y 
} 
<bytecode: 0x0000000013fda7c8> 
<environment: namespace:nnet> 
0

你可以sample那些rownames具有等於該列中的值max值:

mat<-matrix(c(20,0,0,80,80,0, 
       20,0,40,0,40,20, 
       40,0,40,20,20,0, 
       0,80,40,20,20,20),ncol=6,byrow=T) 
rownames(mat)<-c("A","C","G","T") 

set.seed(123) 
apply(mat, 2 , function(x) sample(c(rownames(mat)[ which(x == max(x)) ]) , 1)) 
#[1] "G" "T" "G" "A" "A" "C" 

set.seed(1234) 
apply(mat, 2 , function(x) sample(c(rownames(mat)[ which(x == max(x)) ]) , 1)) 
#[1] "G" "T" "G" "A" "A" "T" 

附:我不知道爲什麼你使用list對象構造矩陣數據 - 矩陣是向量。