R 如何使0保持为矩阵中的0
我使用以下代码生成一个矩阵R 如何使0保持为矩阵中的0,r,loops,if-statement,matrix,R,Loops,If Statement,Matrix,我使用以下代码生成一个矩阵 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
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))
m <- old_subs + new_subs
sz[j,i] <- m[1,1]
n <- m
}
}
return (sz)
}
>randomdiv(3, 3, 10)
[,1] [,2] [,3]
[1,] 11 13 12
[2,] 6 8 5
[3,] 12 11 9
我用
ifelse
函数尝试了几种不同的策略,但我认为它只将列作为一个整体处理,因此如果有0,整个列将不会发生任何变化,而我需要单独处理列中的每个值。您只需要使用if()
使用else
并跳过几行代码(如果有0:
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)
if(old_subs>0){
num_chrom <- rep(1 / nchrom, nchrom)
new_subs <- rmultinom(1, size * nchrom / 2, prob = c(num_chrom))
m <- old_subs + new_subs
sz[j,i] <- m[1,1]
} else sz[j,i] <- old_subs
n <- m
}
}
return (sz)
}
randomdiv(3, 3, 2)
# [,1] [,2] [,3]
# [1,] 2 2 0
# [2,] 1 2 4
# [3,] 1 1 0
randomdiv你能解释一下randomdiv应该做什么吗?现在你的问题很难回答understand@nist我明白这不容易理解,我发现很难简化它,因为仅仅输入数字并不能实现相同的功能randomdiv()
根据代码顶行中的参数生成一个矩阵。因此,size
参数通过rbinomal
将每行的大小大致减半(由nchrom
定义,在我给出的示例中,这是3)。然后我使用r多项式
生成值,这些值应该添加到rbinom
生成的值中,这个组合数字是矩阵中的实际输出值-它只是循环添加一个示例所需输出?
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)
if(old_subs>0){
num_chrom <- rep(1 / nchrom, nchrom)
new_subs <- rmultinom(1, size * nchrom / 2, prob = c(num_chrom))
m <- old_subs + new_subs
sz[j,i] <- m[1,1]
} else sz[j,i] <- old_subs
n <- m
}
}
return (sz)
}
randomdiv(3, 3, 2)
# [,1] [,2] [,3]
# [1,] 2 2 0
# [2,] 1 2 4
# [3,] 1 1 0