且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将自定义函数加载到 R 中的 foreach 循环中?

更新时间:2022-03-17 03:13:33

我不知道为什么你的 foreach 方法不起作用,而且我也不确定你实际上是什么计算.无论如何,您可以使用 parallel::parLapply() 尝试这种替代方法,它似乎有效:

I'm not sure why your foreach approach doesn't work, andd I'm also not sure what you're actually calculating. Anyway, you may try this alternative approach using parallel::parLapply() which seems to work:

首先,我使用 rm(list=ls()) 清除了工作区,然后我运行了 这个答案,他们在其中创建了 "corStruct" 类和 corHaversine 方法,以便在工作区和 Data 中使用它> 下面,准备clusterExport().

First, I cleared workspace using rm(list=ls()), then I ran the entire first codeblock of this answer where they create "corStruct" class and corHaversine method to have it in workspace as well as the Data below, ready for clusterExport().

library(parallel)
cl <- makeCluster(detectCores() - 1)
clusterEvalQ(cl, library(nlme))
clusterExport(cl, ls())
r <- parLapply(cl=cl, X=1:2, fun=function(i) {
  gls(disp ~ wt, 
      correlation=corHaversine(form= ~ lon + lat, mimic="corSpher"),
      data=mtcars)
})
stopCluster(cl)  ## stop cluster
r  ## result
# [[1]]
# Generalized least squares fit by REML
# Model: disp ~ wt 
# Data: mtcars 
# Log-restricted-likelihood: -166.6083
# 
# Coefficients:
#   (Intercept)          wt 
# -122.4464    110.9652 
# 
# Correlation Structure: corHaversine
# Formula: ~lon + lat 
# Parameter estimate(s):
#   range 
# 10.24478 
# Degrees of freedom: 32 total; 30 residual
# Residual standard error: 58.19052 
# 
# [[2]]
# Generalized least squares fit by REML
# Model: disp ~ wt 
# Data: mtcars 
# Log-restricted-likelihood: -166.6083
# 
# Coefficients:
#   (Intercept)          wt 
# -122.4464    110.9652 
# 
# Correlation Structure: corHaversine
# Formula: ~lon + lat 
# Parameter estimate(s):
#   range 
# 10.24478 
# Degrees of freedom: 32 total; 30 residual
# Residual standard error: 58.19052 


数据:

set.seed(42)  ## for sake of reproducibility
mtcars <- within(mtcars, {
  lon <- runif(nrow(mtcars))
  lat <- runif(nrow(mtcars))
  marker <- c(rep(1, nrow(mtcars)/2), rep(2, nrow(mtcars)/2))
})