简体   繁体   English

如何更快地运行循环R程序?

[英]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 .我正在使用以下r code来计算每个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.但是我想对大量生成的数据集执行此过程,例如a = 10000并将整个循环迭代1000次。 How can I speed up the the following program?如何加速以下程序? Am I able to use apply function instead of for function?我可以使用apply函数而不是for函数吗?

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 的计算放到一个函数中,然后使用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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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