如果在R中的其他内部循环

时间:2016-02-06 05:25:14

标签: r if-statement for-loop

我需要在R中的for循环中间创建一个if / else语句。

我正在尝试用R中的3-3设计创建一个假设的1期临床试验。我从sample1~二项式(3,x / 10)开始,x从1开始。如果sample1 = 0,则增加x按1并再次取样。当sample1> 0,取第二个样本,sample2~二项式(3,x / 10),在相同的x值。如果sample2 = 0,则增加x,然后再次取样1。如果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

看看结果,我得到的只是零,所以有些事情是不对的。有人可以请你帮忙。 感谢。

2 个答案:

答案 0 :(得分:0)

也许这就是你要找的东西:

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&gt; 0和sample2> 0。只有这样,循环才会变为i + 1,x将重置为1.

答案 1 :(得分:0)

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)
})

这是你想要的结果吗?