2013-07-22 111 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对象构造矩阵数据 - 矩阵是向量。