2016-02-06 24 views
0

我需要R.否則,如果在for循環中的R

創造的中間的if/else語句for循環

我想創建一個假設相3-3設計的1個臨牀試驗R.我從sample1〜binomial(3,x/10)開始,x從1開始。如果sample1 = 0,則將x增加1並再次取樣。當sample1> 0時,採用第二個採樣,sample2〜binomial(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 

看着結果,我得到的都是零,所以有些東西是不對的。有人可以請協助。 謝謝。

+0

我得到零和使用相同的代碼 – jalapic

+0

在使用相同的代碼,我也得到了零和1。只需要添加,當使用賦予隨機值的函數時,您應該設置特定的種子,以便您的輸出具有可重現性。 –

+0

但是不應該有任何0,因爲我認爲我有x從1開始。 –

回答

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 

什麼這些變化做我是每一個,你會繼續服用SAMPLE1和SAMPLE2直到SAMPLE1> 0和SAMPLE2> 0。只有這樣,環路將改變爲i + 1和x復位到1

+0

謝謝!這似乎給了我想要的東西。 –

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

是您想要的結果嗎?