Skip to Content

In R - Change For Loops into "apply", "tapply", "sapply" and etc

Thanks for reading this thread. I'm relatively new to R so this question might seem stupid.

So, I have a data set on product prices. It is a 240 by 1,000 matrix. Each column represents a unique product and each row gives price info of the 1,000 at a specific month. I'm trying to re-sample the data set and get a new matrix of the same dimensions.

  • My data is saved as "data"

  • I would want to save the bootstrapped results in "newdata", which is an empty 240x1,000 matrix

Here's my code:

for (month in 1:num.months)
{  
  for (n in 1:num.products)
  {
    newdata[month, n] <- mean(sample(data[month, ], 
                                size = num.productss,
                     replace = TRUE));
  }
 }

This works but the For Loops make things really slow. It would be great if someone can point out how I could improve the speed by using apply, sapply, tapply, and etc. Thanks.