Reputation: 131
I have written the following code:
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)
}
Which returns the following matrix:
> 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
I did originally want for any occurrence of a 0 to be propagated along that particular row for the remainder of the columns. What I now want to do is find where a 0 occurs, and for the entire matrix to only return 0s past that point. I could stop the matrix once a 0 occurs but I want to keep the same number of columns for replicated matrices, so it's going to be easier if I can just fill the matrix with 0s from the point that the first one occurs. For example, in the output shown here, the matrix would only show 0s from the 2nd column, onwards, for all rows because the first 0 occurred at [7,1]
If anyone has any ideas, it would be much appreciated.
Upvotes: 1
Views: 40
Reputation: 48201
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
Upvotes: 1