map()可以接受具有多个输入的函数吗?

时间:2019-06-20 15:27:25

标签: r function dictionary purrr

我想按组对分层的多个结果和预测指标循环使用glm / lm。 purrr软件包中的nest()和map()函数似乎为分层分析提供了一种优雅的解决方案。但是,当我使用需要多个输入的自定义函数时,map()似乎不起作用。

在我所见的purrr的map()的几乎所有教程中,回归模型示例都是静态的-因变量和自变量在函数中明确定义。因为我想循环遍历数十个结果和预测变量,所以我试图编写一个可以迭代不同组合的lm()函数。

library(dplyr)
library(broom)
library(tidyr)
library(purrr)

# example data set
set.seed(20)
df <- data.frame(
  out = rep(c(0,1),5,replace=TRUE),
  pre = sample(c(1:4),10,replace = TRUE),
  var1 = sample(c(1:2),10,replace = TRUE),
  var2 = sample(c(1:50),10,replace = TRUE),
  group = sample(c(1:2),10,replace = TRUE)
)

explicit_fun<-function(data){
  glm(out ~ pre + var1 + var2, data=data, family = binomial())
}

input_fun<-function(data, outcome, predictor, covariate){
  glm(as.formula(paste(outcome,"~",predictor,"+",paste(covariate,collapse = "+"))),data=data,family = binomial())
}

# nesting the data set
df_by_group<-df%>%
  group_by(group)%>%
  nest()

与显式功能配合正常

models <- df_by_group%>%
  mutate(mod=purrr::map(data,explicit_fun))
models <- models%>%
  mutate(
         glance_glm=purrr::map(mod,broom::glance),
         tidy_glm=purrr::map(mod,broom::tidy),
         augment_glm=purrr::map(mod,broom::augment)
         )
unnest(models,data)
unnest(models,glance_glm,.drop = TRUE)%>% View()
unnest(models,tidy_glm) %>% View()

使用具有多个输入的功能时它将停止工作

models<-df_by_group%>%
mutate(mod=purrr::map(data,input_fun(data=.,outcome="out",predictor="pre",covariate=c("var1","var2"))))

我希望input_fun的工作方式与explicit_fun相同,但是我收到以下错误消息:

Error in mutate_impl(.data, dots) : 
  Evaluation error: Can't convert a `glm/lm` object to function
Call `rlang::last_error()` to see a backtrace.

1 个答案:

答案 0 :(得分:2)

您需要将一个函数传递给map()。现在,您正在第二个参数中调用函数,而不传递函数。解决此问题的最快方法是使用公式语法创建函数。试试

models <- df_by_group%>%
  mutate(mod=purrr::map(data, ~input_fun(data=.,outcome="out",predictor="pre",covariate=c("var1","var2"))))

这会延迟对input_fun的评估,直到地图实际发生并正确填充.值为止。

相关问题