繁体   English   中英

如何使此R代码(用于循环)更有效?

[英]How to make this R code (for loop) more efficient?

我正在进行仿真研究,并编写了以下R代码。 是否有编写这种代码而不使用两个for循环,或者使其更有效(运行更快)的方法?

S = 10000
n = 100
v = c(5,10,50,100)
beta0.mle = matrix(NA,S,length(v))  #creating 4 S by n NA matrix 
beta1.mle = matrix(NA,S,length(v))
beta0.lse = matrix(NA,S,length(v))
beta1.lse = matrix(NA,S,length(v))
for (j in 1:length(v)){
  for (i in 1:S){
    set.seed(i)
    beta0 = 50
    beta1 = 10
    x = rnorm(n)
    e.t = rt(n,v[j])
    y.t = e.t + beta0 + beta1*x
    func1 = function(betas){
      beta0 = betas[1]
      beta1 = betas[2]
      sum = sum(log(1+1/v[j]*(y.t-beta0-beta1*x)^2))
      return((v[j]+1)/2*sum)
    }
    beta0.mle[i,j] = nlm(func1,c(1,1),iterlim = 1000)$estimate[1]
    beta1.mle[i,j] = nlm(func1,c(1,1),iterlim = 1000)$estimate[2]
    beta0.lse[i,j] = lm(y.t~x)$coef[1]
    beta1.lse[i,j] = lm(y.t~x)$coef[2]
  }
}

第二个for循环内的函数func1用于nlm函数(当错误分布为t时查找mle)。 我想在R中使用parallel包,但没有找到任何有用的功能。

要得到任何东西跑R中更快的关键是更换for与矢量化功能的循环(如apply家庭)。 此外,对于任何编程语言,您都应该查找使用相同参数多次调用昂贵函数(例如nlm )的地方,并查看可以在其中存储结果而不是每次都重新计算的地方。

在这里,我就像定义参数一样开始。 同样,由于beta0beta1始终为5010beta0在此处定义它们。

S <- 10000
n <- 100
v <- c(5,10,50,100)
beta0 <- 50
beta1 <- 10

接下来,我们将在循环外部定义func1以避免每次都重新定义它。 func1现在有两个额外的参数, vyt以便可以用新值调用它。

func1 <- function(betas, v, y.t, x){
  beta0 <- betas[1]
  beta1 <- betas[2]
  sum <- sum(log(1+1/v*(y.t-beta0-beta1*x)^2))
  return((v+1)/2*sum)
}

现在,我们实际上做了真正的工作。 我们没有嵌套循环,而是使用嵌套的apply语句。 外部lapply将为v每个值创建一个列表,内部vapply将为S每个值beta1.lse要获取的四个值的矩阵( beta0.mlebeta1.mlebeta0.slebeta1.lse ) 。

values <- lapply(v, function(j) vapply(1:S, function(s) {
  # This should look familiar, it is taken from your code
  set.seed(s)
  x <- rnorm(n)
  e.t <- rt(n,j)
  y.t <- e.t + beta0 + beta1*x
  # Rather than running `nlm` and `lm` twice, we run it once and store the results
  nlmmod <- nlm(func1,c(1,1), j, y.t, x, iterlim = 1000)
  lmmod <- lm(y.t~x)
  # now we return the four values of interest
  c(beta0.mle = nlmmod$estimate[1],
    beta1.mle = nlmmod$estimate[2],
    beta0.lse = lmmod$coef[1],
    beta1.lse = lmmod$coef[2])
}, numeric(4)) # this tells `vapply` what to expect out of the function
)

最后,我们可以将所有内容重组为四个矩阵。

beta0.mle <- vapply(values, function(x) x["beta0.mle", ], numeric(S))
beta1.mle <- vapply(values, function(x) x["beta1.mle", ], numeric(S))
beta0.lse <- vapply(values, function(x) x["beta0.lse.(Intercept)", ], numeric(S))
beta1.lse <- vapply(values, function(x) x["beta1.lse.x", ], numeric(S))

最后,根据您为什么使用S索引设置种子,可以重新组织它以使其运行得更快。 如果知道使用rnorm生成x种子很重要,那么我可以做的最好。 但是,如果仅是为了确保对所有v值都在相同的x值上进行测试,则可能会有更多的重组,我们可以这样做,而使用replicate可以提高速度。

暂无
暂无

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

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