Michinio
Michinio

Reputation: 95

random number inside for loop

This is driving me crazy already and by now I'm absolutely hopeless :(

Here is the matrix draw (don't pay attention to NAs, later I need those columns):

      [,1] [,2] [,3] [,4] [,5]  
[1,]    1    0   NA   NA   NA  
[2,]    2   20   NA   NA   NA  
[3,]    2   30   NA   NA   NA  
[4,]    2   40   NA   NA   NA  
[5,]    1   50   NA   NA   NA  
[6,]    2   70   NA   NA   NA  
[7,]    2   80   NA   NA   NA  
[8,]    2   90   NA   NA   NA  
[9,]    1  100   NA   NA   NA
[10,]   2  120   NA   NA   NA
[11,]   2  130   NA   NA   NA
[12,]   2  140   NA   NA   NA

so, depending on column 1 I need to write number in column 3 from normal distribution. But in 6% of the cases it have to be 0.

This is how I thought to deal with it (by now it's only when draw[i,1]==2):

for (i in 1:nrow(draw))
{
    p <- runif(1, min=0, max=1)
    if (draw[i,2]==2 && p>0.06) 
    {   
        draw[i,3] <- rnorm(1, mean=17, sd=7.5)} else {draw[i,3]<-0}

    if (draw[i,1]==1) {draw[i,3] <- rnorm(1, mean=11, sd=3)}
    if (draw[i,1]==3) {draw[i,3] <- rnorm(1, mean=17, sd=15)}
    if (draw[i,3]<1 && draw[i,3]!=0) {draw[i,3] <- 1} else {draw[i,3] <- ceiling(draw[i,3])
}
}

and there problems come: 1. I notices p (which have to be random number I guess) is always the same 2. all draw[i,3] where draw[1,2]==2 are 0. This is strange, because it happens even when p>0.06:

      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    0   19   NA   NA
 [2,]    2   20    0   NA   NA
 [3,]    2   30    0   NA   NA
 [4,]    2   40    0   NA   NA
 [5,]    1   50   11   NA   NA
 [6,]    2   70    0   NA   NA
 [7,]    2   80    0   NA   NA
 [8,]    2   90    0   NA   NA
 [9,]    1  100    7   NA   NA
[10,]    2  120    0   NA   NA
[11,]    2  130    0   NA   NA
[12,]    2  140    0   NA   NA

why?! what is wrong?

Upvotes: 0

Views: 1177

Answers (1)

Tommy
Tommy

Reputation: 40803

Hmm. You say that when draw[i,1]==2 you want to do something, but in your code you write draw[i,2]==2... That's probably the problem!

# This line might work better:
if (draw[i,1]==2 && p>0.06) 

... but it seems rather messy anyway. Maybe this is what you meant? - barring any bugs I put in there :)

for (i in 1:nrow(draw)) {
  p <- runif(1, min=0, max=1)

  draw[i,3] <- if (p <= 0.06) 0
    else switch(draw[i,1], 
      rnorm(1, mean=11, sd=3),   # 1
      rnorm(1, mean=17, sd=7.5), # 2
      rnorm(1, mean=17, sd=15)   # 3
    )

  draw[i,3] <- if (draw[i,3]<1 && draw[i,3]!=0) 1 else ceiling(draw[i,3])
}

Upvotes: 3

Related Questions