title: How to vectorize a for loop in R
body: <p>I'm trying to clean this code up and was wondering if anybody has any suggestions on how to run this in R without a loop.  I have a dataset called data with 100 variables and 200,000 observations.  What I want to do is essentially expand the dataset by multiplying each observation by a specific scalar and then combine the data together.  In the end, I need a data set with 800,000 observations (I have four categories to create) and 101 variables.  Here's a loop that I wrote that does this, but it is very inefficient and I'd like something quicker and more efficient.  </p>
  
  <pre><code>datanew &lt;- c()
  for (i in 1:51){
    for (k in 1:6){
      for (m in 1:4){
  
        sub &lt;- subset(data,data$var1==i &amp; data$var2==k)
  
        sub[,4:(ncol(sub)-1)] &lt;- filingstat0711[i,k,m]*sub[,4:(ncol(sub)-1)]
  
        sub$newvar &lt;- m
  
        datanew &lt;- rbind(datanew,sub)
  
      }
    }
  }
  </code></pre>
  
  <p>Please let me know what you think and thanks for the help.  </p>
  
  <p>Below is some sample data with 2K observations instead of 200K</p>
  
  <pre><code># SAMPLE DATA
  #------------------------------------------------#
    mydf &lt;- as.data.frame(matrix(rnorm(100 * 20e2), ncol=20e2, nrow=100))
    var1 &lt;- c(sapply(seq(41), function(x) sample(1:51)))[1:20e2]
    var2 &lt;- c(sapply(seq(2 + 20e2/6), function(x) sample(1:6)))[1:20e2]
    #----------------------------------#
    mydf &lt;- cbind(var1, var2, round(mydf[3:100]*2.5, 2))
    filingstat0711 &lt;- array(round(rnorm(51*6*4)*1.5 + abs(rnorm(2)*10)), dim=c(51,6,4))
  #------------------------------------------------#
  </code></pre>