我写了以下代码:
randomdiv <- function(nchrom, ndivs, size) {
sz <- matrix(nrow = nchrom, ncol = ndivs)
for (j in 1:nchrom) {
n <- size
for (i in 1:ndivs)
{
old_subs <- rbinom (1, n, 0.5)
num_chrom <- rep(1 / nchrom, nchrom)
new_subs <- rmultinom(1, size * nchrom / 2, prob = c(num_chrom))
total_subs <- cbind(old_subs, new_subs)
m <- as.matrix(ifelse(total_subs[,1]>0, total_subs[,1] + total_subs[,2], 0))
sz[j,i] <- m[1,1]
n <- m
}
}
return (sz)
}
返回以下矩阵:
> randomdiv(10, 10, 3)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2 2 5 4 2 3 3 3 0 0
[2,] 3 3 3 2 0 0 0 0 0 0
[3,] 2 5 3 1 2 2 0 0 0 0
[4,] 4 3 4 3 4 5 3 0 0 0
[5,] 2 3 6 4 3 3 5 4 5 2
[6,] 2 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0
[8,] 2 0 0 0 0 0 0 0 0 0
[9,] 2 0 0 0 0 0 0 0 0 0
[10,] 3 6 7 4 4 2 1 0 0 0
我最初希望任何出现的0都沿着该特定行传播到其余列。我现在想要做的是找到0出现的位置,并且整个矩阵只返回超过该点的0。我可以在0出现时停止矩阵但是我想为复制矩阵保留相同数量的列,所以如果我可以从第一个出现的点填充矩阵0更容易。例如,在此处显示的输出中,对于所有行,矩阵仅从第2列开始显示0,因为前0发生在[7,1]
如果有人有任何想法,我们将不胜感激。
答案 0 :(得分:1)
set.seed(123)
(M <- randomdiv(10, 10, 3))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 3 4 5 7 3 0 0 0 0 0
# [2,] 2 4 6 2 4 1 2 2 2 3
# [3,] 2 3 3 2 1 2 2 2 5 2
# [4,] 6 3 5 7 5 6 8 5 6 5
# [5,] 2 3 5 4 3 4 4 3 3 3
# [6,] 0 0 0 0 0 0 0 0 0 0
# [7,] 2 3 2 5 3 5 5 7 5 5
# [8,] 3 2 2 1 4 4 4 3 1 0
# [9,] 1 0 0 0 0 0 0 0 0 0
# [10,] 5 3 1 4 3 2 5 3 0 0
M[cumsum(c(M) == 0) > 0] <- 0
M
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 3 0 0 0 0 0 0 0 0 0
# [2,] 2 0 0 0 0 0 0 0 0 0
# [3,] 2 0 0 0 0 0 0 0 0 0
# [4,] 6 0 0 0 0 0 0 0 0 0
# [5,] 2 0 0 0 0 0 0 0 0 0
# [6,] 0 0 0 0 0 0 0 0 0 0
# [7,] 0 0 0 0 0 0 0 0 0 0
# [8,] 0 0 0 0 0 0 0 0 0 0
# [9,] 0 0 0 0 0 0 0 0 0 0
# [10,] 0 0 0 0 0 0 0 0 0 0