r语言 - 使用 multidplyr 调用带有 dplyr::d o 中的参数的函数



我正在尝试使用multidplyr来加快从regression适合中获得residuals。我创建了一个适合regression模型的function来获取residuals,除了数据之外,它还获得了另外两个参数。

以下是function

func <- function(df,reg.mdl,mdl.fmla)
{
  if(reg.mdl == "linear"){
    df$resid <- lm(formula = mdl.fmla, data = df)$residuals
  } else if(reg.mdl == "poisson"){
    df$resid <- residuals(object = glm(formula = mdl.fmla,data = df,family = "poisson"),type='pearson')
  }
  return(df)
}

下面是一个示例数据,我将尝试我的multidplyr方法:

set.seed(1)
ds <- data.frame(group=c(rep("a",100), rep("b",100),rep("c",100)),sex=rep(sample(c("F","M"),100,replace=T),3),y=rpois(300,10))
model.formula <- as.formula("y ~ sex")
regression.model <- "poisson"

这是multidplyr方法:

ds %>% partition(group) %>% cluster_library("tidyverse") %>%
  cluster_assign_value("func", func) %>%
  do(results = func(df=.,reg.mdl=regression.model,mdl.fmla=model.formula)) %>% collect() %>% .$results %>% bind_rows()

不过,这会引发此错误:

Error in checkForRemoteErrors(lapply(cl, recvResult)) : 
  3 nodes produced errors; first error: object 'regression.model' not found
In addition: Warning message:
group_indices_.grouped_df ignores extra arguments

所以我想我把论点传递给func的方式是错误的do

知道正确的方法是什么吗?

由于集群环境中没有此类对象而导致的错误。因此,需要将变量分配给聚类过程:

ds %>%
  partition(group) %>%
  cluster_library("tidyverse") %>%
  cluster_assign_value("func", func) %>%
  cluster_copy(regression.model) %>%
  cluster_copy(model.formula) %>%
  do(results = func(
    df = .,
    reg.mdl = regression.model,
    mdl.fmla = model.formula
  )) %>%
  collect() %>%
  .$results %>%
  bind_rows()

或者另一种方式(我更喜欢在链之前设置集群):

CL <- makePSOCKcluster(3)
clusterEvalQ(cl = CL, library("tidyverse"))
clusterExport(cl = CL, list("func", "regression.model", "model.formula"))
ds %>%
  partition(group, cluster = CL) %>%
  do(results = func(
    df = .,
    reg.mdl = regression.model,
    mdl.fmla = model.formula
  )) %>%
  collect() %>%
  .$results %>%
  bind_rows()
stopCluster(CL)

相关内容

  • 没有找到相关文章

最新更新