1

给定一个矩阵,提取具有最大值的列的行名是一个常见问题。

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)之间随机选择时遇到问题,其中两者在第 3 列中都有最大值和 4. 对脚本的任何帮助表示赞赏。

4

3 回答 3

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"部分对于以随机方式解决关系至关重要。

于 2013-07-22T15:10:34.007 回答
2

考虑阅读 的文档which.max,其中建议使用which.is.maxfrom nnet。要么借用那个算法,要么使用那个包。

> 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>
于 2013-07-22T15:10:02.710 回答
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"

ps 我不确定为什么要使用list对象构造矩阵数据 - 矩阵是向量。

于 2013-07-22T15:13:25.347 回答