Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
If-Else在R中为循环 我需要在R.中for循环中创建一个I/ER语句_R_If Statement_For Loop - Fatal编程技术网

If-Else在R中为循环 我需要在R.中for循环中创建一个I/ER语句

If-Else在R中为循环 我需要在R.中for循环中创建一个I/ER语句,r,if-statement,for-loop,R,If Statement,For Loop,我试图创建一个假想的1期临床试验,采用R中的3-3设计。我从样本1~二项式(3,x/10)开始,x从1开始。如果样本1=0,则将x增加1,然后再次取样。当sample1>0时,在相同的x值下,取第二个样本sample2~二项(3,x/10)。如果样本2=0,则增加x,然后再次获取样本1。如果sample2>0,则打印该x值。我想这样做10次,看看x值是多少。下面是我的代码 reps <- 10 MTD <- numeric(reps) for (i in 1:reps) { x

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

reps也许这就是你想要的:

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

reps
MTD我使用相同的代码得到零和一在使用相同的代码时,我也得到了零和一。另外,在使用随机值的函数时,您应该设置一个特定的种子,以便输出是可复制的。但不应该有任何0,因为我认为x从1开始。MTD只有在sample2>0时才会改变,如果10次重复返回的sample1或sample2等于0,MTD[I]保持不变(0)下一个循环开始了,好的。我希望它继续采样(将x增加1),直到sample2>0,将该x值保存在MTD[I]中,然后再次启动循环(从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
    }
})
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)
})