开始使用免费开始使用

捕获建模错误

出生时预期寿命是衡量人群健康状况的重要指标。

您是一名公共卫生研究顾问。您的客户想了解每花费 1 美元医疗支出,预期寿命能增加多少。您已收集了 2001–2021 年全球各国的预期寿命(以年为单位)及其人均医疗支出数据。统计顾问已经编写了代码,为每个国家的数据拟合回归模型。不过,数据中存在缺失值,导致模型拟合时报错。

您的工作区中有一个数据框列表 ls_df,其中每个元素对应一个国家的数据。您计划使用 parLapply() 并配合 tryCatch() 来捕获错误实现并行化。已为您加载 parallel 包。

本练习是课程的一部分

R 并行编程

查看课程

练习说明

  • 为 error 参数提供一个函数。该函数应只接受一个参数 e,并使用 paste()e 前面加上字符串 "Error!"
  • 修改 fit_lm(),检查 model 是否为包含错误信息的字符字符串。
  • 使用 6 个内核创建一个集群。
  • 使用 parLapply() 并行地将 fit_lm() 应用于列表 ls_df

交互式实操练习

通过完成这段示例代码来试试这个练习。

fit_lm <- function (df) {
  model <- tryCatch(lm(life_expectancy ~ health_exp_per_capita, data = df),
# Supply a function that pastes "Error!" and one argument, e
                    error = ___)                   
# If model is character (error) return model else return model coefficient
  if (___) return(model)
  else return(coef(model)[2])
}
# Make a cluster of six cores
cluster <- ___(___)
# Apply fit_lm in parallel to ls_df using cluster
ls_mod <- parLapply(___, ___, ___)
stopCluster(cluster)
                    
print(paste(sum(sapply(ls_mod, is.numeric)), "models fit and", sum(sapply(ls_mod, is.character)), "errors caught!"))
编辑并运行代码