如何将自定义函数加载到 R 中的 foreach 循环中? [英] How can I load custom functions into foreach loop in R?

查看:66
本文介绍了如何将自定义函数加载到 R 中的 foreach 循环中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行具有特定空间相关结构的 gls 模型,该结构来自修改 nlme 包/从此 post(这篇文章的答案创建了允许实现相关性的新函数结构体).不幸的是,当我通过 foreach 循环运行它时,我无法让这个空间相关结构起作用:

I am trying to run gls models with a specific spatial correlation structure that comes from modifying the nlme package/ building new functions in the global environment from this post (the answer from this post that creates new functions which allows for the implementation of the correlation structure). Unfortunately I cannot get this spatial correlation structure to work when I run this through a foreach loop:

#setup example data
data("mtcars")
mtcars$lon = runif(nrow(mtcars)) #include lon and lat for the new correlation structure
mtcars$lat = runif(nrow(mtcars))
mtcars$marker = c(rep(1, nrow(mtcars)/2), rep(2, nrow(mtcars)/2)) #values for iterations

#set up cluster
detectCores()
cl <- parallel::makeCluster(6, setup_strategy = "sequential")
doParallel::registerDoParallel(cl)

#run model
list_models<-foreach(i=1:2, .packages=c('nlme'), .combine = cbind,
                     .export=ls(.GlobalEnv)) %dopar% {
                    
                       .GlobalEnv$i <- i
                       
                       model_trial<-gls(disp ~ wt, 
                                             correlation = corHaversine(form=~lon+lat, 
                                                                        mimic="corSpher"),
                                             data = mtcars)
                     }


stopCluster(cl)

当我运行它时,我收到错误消息:

When I run this I get the error message:

Error in { : 
  task 1 failed - "do not know how to calculate correlation matrix of "corHaversine" object"
In addition: Warning message:
In e$fun(obj, substitute(ex), parent.frame(), e$data) :
  already exporting variable(s): corHaversine, mtcars, path_df1

该模型在添加相关结构的情况下运行良好:

The model works fine with the added correlation structure :

correlation = corHaversine(form=~lon+lat,mimic="corSpher")

在正常循环中.任何帮助将不胜感激!

in a normal loop. Any help would be appreciated!

推荐答案

我不知道为什么你的 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))
})

这篇关于如何将自定义函数加载到 R 中的 foreach 循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆