给定一个二进制矩阵 B
,通常可以使用Blist <- apply(B==1, 1, which)
来按行列出 1 的列索引列表。然而,当例如 rowSums(B)[1] == rowSums(B)[2]
时,这种方式就行不通了。
下面是一个适用的示例:
> B <- matrix(c(1,1,0,0,1,0,0,0,1),3,3)
> B
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 1 1 0
[3,] 0 0 1
> Blist <- apply(B==1, 1, which)
> Blist
[[1]]
[1] 1
[[2]]
[1] 1 2
[[3]]
[1] 3
以下是一种无法正常运行的示例:
> B <- matrix(c(1,0,0,0,1,0,0,0,1),3,3)
> B
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
> Blist <- apply(B==1, 1, which)
> Blist
[1] 1 2 3
在这种情况下,期望的结果是:
> Blist
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
我该如何修改
Blist <- apply(B==1, 1, which)
,以使结果始终组织为列表?