title: Efficient way to vectorize R for loops
body: <p>How can the following R code be vectorized to reduce computing time?</p>
  
  <pre><code>q = matrix(0,n,p)
  for(u in 1 : n){
      q1 &lt;- matrix(0,p,1)
    for(iprime in 1 : n){
      for(i in 1 : n){
        if(cause[iprime]==1 &amp; cause[i]&gt;1 &amp; (time[i]&lt;time[u]) &amp; (time[u] &lt;= time[iprime])){
            q1 = q1 + (covs[i,] - S1byS0hat[iprime,])*G[iprime]/G[i]*expz[i]/S0hat[iprime]
        }
      }
  
    }
      q[u,] = q1/(m*m)
  }
  </code></pre>
  
  <p>Following values could be used as an example:</p>
  
  <pre><code>n = 2000
  m = 500
  p=3
  G = runif(n)
  time = runif(n,0.01,5)
  cause = c(rep(0,600),rep(1,1000),rep(2,400))
  covs = matrix(rnorm(n*p),n,p)
  S1byS0hat = matrix(rnorm(n*p),n,p)
  S0hat = rnorm(n)
  expz = rnorm(n)
  </code></pre>