简体   繁体   English

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

[英]If Else Inside For Loop in R

I need to create a if/else statement in the middle of a for loop in R. 我需要在R中的for循环中间创建一个if / else语句。

I am trying to create a hypothetical phase 1 clinical trial with 3-3 design in R. I start with sample1 ~ binomial(3, x/10), with x starting at 1. If the sample1 = 0, increase x by 1 and take a sample again. 我试图用R中的3-3设计创建一个假设的1期临床试验。我从sample1〜binomial(3,x / 10)开始,x从1开始。如果sample1 = 0,则将x增加1并再次取样。 When sample1 > 0, take a second sample, sample2 ~ binomial(3, x/10), at the same x value. 当sample1> 0时,以相同的x值获取第二个样本sample2〜binomial(3,x / 10)。 If sample2=0, increase x, and take sample1 again. 如果sample2 = 0,则增加x,然后再次获取sample1。 If sample2>0, print that x value. 如果sample2> 0,则打印该x值。 I want to do this 10 times and see what the x value for is. 我想做10次,看看x值是多少。 Below is my code. 下面是我的代码。

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

Looking at the results, all I get are zeros so something is not right. 看结果,我得到的都是零,所以有些不对劲。 Could someone please assist. 有人可以帮忙。 Thanks. 谢谢。

Maybe this is what you are looking for: 也许这就是您想要的:

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

What these changes do is for every i, you will keep taking sample1 and sample2 until sample1 > 0 and sample2 >0. 这些变化对每个i而言,您将继续获取sample1和sample2,直到sample1> 0和sample2> 0。 Only then the loop will change to i+1 and x is reset to 1. 只有这样,循环才会变为i + 1,x重置为1。

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

Well, I split sample1 and sample2 as independent parameters to make it difference as shows below. 好吧,我将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)
})

Is it your desired result? 这是您想要的结果吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM