user3022875
user3022875

Reputation: 9018

How to optimize my code so loops are not used

I am running an experiment. I sample from number 1 to 6 and I do this 3 times. On each run of the experiment I implement some logic to get a "main" vector. Then I repeat the experiment 5 times. My code is:

 main<- vector("numeric",5)

 for (i in 1:5)
 {
    s<-sample(c(1,2,3,4,5,6), 3, replace = FALSE)
   print(s) 
    if(s[1]>3)
   {
       main[i]<-s[1]
      }else
     {
       if(s[2]>3)
       {
         main[i]<-s[2]
       }
      else
      {
        main[i]<-s[3]
       }
     }
 }

print(main)

When you run that you will see something like:

 [1] 5 1 2
 [1] 5 2 1
 [1] 6 1 4
 [1] 3 4 1
 [1] 2 5 1

 > print(main)
 [1] 5 5 6 4 5

The main vector is produced by following the rules below:

  1. If the 1st element of the vector is >3 then the result is the first element
  2. If the 1st element of the vector is <3 AND the 2nd element is >3 then the result is the 2nd element
  3. Otherwise the result is the 3rd element

What I am wondering is there a more concise, vectorized, more efficient way of doing this? Using vecotors instead of loops and if statements, etc...

Thank you.

Upvotes: 2

Views: 66

Answers (1)

gagolews
gagolews

Reputation: 13076

I would rewrite your code as follows:

replicate(5, {
   s<-sample(c(1,2,3,4,5,6), 3, replace = FALSE)
   s[c(which(s[1:2] > 3), 3)[1]] # return 1st, 2nd or 3rd element
})

c(which(s[1:2] > 3), 3)[1] returns 1 if s[1] > 3, 2 if s[2] > 3, and 3 otherwise. Thus, s[c(...)[1]] selects either 1st, 2nd, or 3rd element accordingly.

Upvotes: 3

Related Questions