简体   繁体   中英

How to run for loop R program faster?

I am using the following r code to compute the loglikelihood for left side and right side for each i = 1,2,...,200 .

But I want to do this procedure for large number of generated dataset, for instance a = 10000 and iterate the entire loop for 1000 times. How can I speed up the the following program? Am I able to use apply function instead of for function?

Thank you in advance!

n1 = 100
n2 = 100
a = 1000 
n= n1 + n2
# number of simulated copies of y
  sim.data = matrix(NA, nrow = n, ncol = a)
  for (i in 1:a) {
    #for(j in 1:a){
    sim.data[,i] = c(rnorm(n1, 2, 1), rnorm(n-n1, 4, 1))
    #}
  }
  dim(sim.data)


  # Compute the log-likelihood
  B = ncol(sim.data)
  loglike_profb = matrix(NA, n - 1, B)
  for (j in 1:B) {
    for (i in 1:(n - 1)) {
      loglike_profb[i, j] = -0.5*(sum(((sim.data[1:i,j]) - mean(sim.data[1:i,j]))^2) + sum(((sim.data[(i + 1):n,j]) - mean(sim.data[(i +1):n,j]))^2))
    }
  }

You can put the calculation of the loglike_profb into a function and then use mapply

loglike_profb_func <- function(i,j){
  -0.5*(sum(((sim.data[1:i,j]) - mean(sim.data[1:i,j]))^2) + sum(((sim.data[(i + 1):n,j]) - mean(sim.data[(i +1):n,j]))^2))
}
mapply(loglike_profb_func, rep(1:(n-1),B), rep(1:B,(n-1)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM