我需要在R中的for循环中间创建一个if/for语句。
我试图在R中建立一个假设的第1阶段临床试验,在R中设计3-3。我从sample1 ~二项式(3,x/10)开始,x从1开始,如果sample1 =0时,增加x 1,再取一个样本。当sample1 >0时,以相同的x值取第二个样本,sample2 ~二项式(3,x/10)。如果是sample2=0,增加x,然后再取sample1。如果是sample2>0,则打印该x值。我想做10次,看看x值是什么。下面是我的密码。
reps <- 10
MTD <- numeric(reps)
for (i in 1:reps) {
x <- 1
sample1 <- rbinom(1, 3, x/10)
if (sample1>0) {sample2 <- rbinom(1,3, x/10)
if (sample2>0) {MTD[i] <- (x)} else x<- x+1}
else x <-x+1
}
MTD看看结果,我得到的都是零,所以有些东西不对。有人能帮忙吗。谢谢。
发布于 2016-02-06 06:19:07
也许这就是你要找的:
reps <- 10
MTD <- numeric(reps)
x <- 1
i = 1
while (i < reps) {
sample1 <- rbinom(1, 3, x/10)
if (sample1>0) {
sample2 <- rbinom(1,3, x/10)
if (sample2>0) {
MTD[i] <- (x)
i = i+1
x = 1
} else {
x <- x+1
}
} else {
x <- x+1
}
}
MTD这些更改所做的是,对于每个i,您将一直使用sample1和sample2,直到sample1 >0和sample2 >0为止。只有这样,循环才会更改为i+1,并将x重置为1。
发布于 2016-02-06 06:49:26
MTD <- as.numeric(10)
sapply(seq(MTD), function(i)
{
sample1 <- sample2 <- rbinom(1, 3, i/10)
if(sample1>0){
sample2 <- sample1
}else{
sample2 <- i+1
}
if(sample2>0){
sample2 <- sample1
}else{
sample2 <- i+1
}
})好的,我将sample1和sample2分割为独立的参数,以使其有所不同,如下所示。
MTD <- as.numeric(10)
sapply(seq(MTD), function(i)
{
sample1 <- rbinom(1, 3, i/10)
sample2 <- rbinom(1, 3, i/10)
if(sample1>0){
sample2 <- sample1
}else{
sample2 <- i+1
}
if(sample2>0){
res <- sample1
}else{
res <- i+1
}; return(res)
})这是你想要的结果吗?
https://stackoverflow.com/questions/35237695
复制相似问题