# How to vectorize the following loop code?

#### Marwah Soliman

##### New Member
I have the following code

Code:
for(i in 1:400)
{
if (mydata$quad[i]==1){ mydata$z[i]=rnorm(n=sum(mydata$quad[i]==1),mean=1,1) } else if (mydata$quad[i]==2){

mydata$z[i]=rnorm(n=sum(mydata$quad[i]==2),mean=9,1)
} else
if (mydata$quad[i]==3){ mydata$z[i]=rnorm(n=sum(mydata$quad[i]==3),mean=6,1) } else if (mydata$quad[i]==4){

mydata$z[i]=rnorm(n=sum(mydata$quad[i]==4),mean=4,1)
}else
if (mydata$quad[i]==5){ mydata$z[i]=rnorm(n=sum(mydata$quad[i]==5),mean=1,1) }else if (mydata$quad[i]==6){

mydata$z[i]=rnorm(n=sum(mydata$quad[i]==6),mean=0,1)
}else
if (mydata$quad[i]==7){ mydata$z[i]=rnorm(n=sum(mydata$quad[i]==7),mean=0,1) }else if (mydata$quad[i]==8){

mydata$z[i]=rnorm(n=sum(mydata$quad[i]==8),mean=2,1)
}else
if (mydata$quad[i]==9){ mydata$z[i]=rnorm(n=sum(mydata$quad[i]==9),mean=6,1) }} and I would like to vectorize the code maybe using ifelse statement how can I do that? #### Dason ##### Ambassador to the humans No need for any if or ifelse statement. If the only thing is different I'd the man it's easy enough to just generate standard normal observations and then add the mean for each observation later. That adding part can easily be done using indexing. #### Marwah Soliman ##### New Member I don't understand , what should I do ? #### Dason ##### Ambassador to the humans Code: # Generate fake data mydata <- data.frame(quad = sample(1:9, 400, replace = T)) means <- c(1,9,6,4,1,0,0,2,6) # this works since quad is just 1-9 mydata$means <- means[mydata$quad] # rnorm can take a different mean for each obseration # so we just match up the mean we want for each row... mydata$z <- rnorm(nrow(mydata), mean = mydata$means, 1) # If you didn't want to create the mydata$means column
mydata$z2 <- rnorm(nrow(mydata), mean = means[mydata$quad], 1)
# If you wanted to just add on the means later
mydata$z3 <- rnorm(nrow(mydata), 0, 1) mydata$z3 <- mydata$z3 + mydata$means

#### Dason

##### Ambassador to the humans
Note that I'm making the assumption that you assigning multiple values to a single row was an error in your code. I don't think you should have been using things like "n=sum(mydata$quad==3)" in your rnorm call since you're assigning to the single value mydata$z

#### Marwah Soliman

##### New Member
Oh, really but R did not give me an error !! Thanks again for mentioning this