为什么此“ forkid1”返回null而不是1000项向量?
set.seed(123)
kid1 <- c()
momprob <- rbinom(1000, 1, 1/3)
forkid1 <- for (i in 1:length(momprob)){
if (momprob[i] == 1) {
kid1[i] <-- rbinom(1, 1, 1/2)
} else {kid1[i] <- 0 }
}
forkid1
(R的新手,并试图阅读以前的答案。在此先感谢)
编辑:另外,我还认为rbinom应该返回0和1的列表-为什么我得到-1?
答案 0 :(得分:0)
在这里,我们需要检查“ kid1”,而不要分配for
循环
kid1 <- integer(1000)
for (i in 1:length(momprob)){
if (momprob[i] == 1) {
kid1[i] <- -rbinom(1, 1, 1/2)
} else {kid1[i] <- 0 }
}
head(kid1)
#[1] 0 0 0 -1 0 0