【问题标题】:Can map() take functions with multiple inputs?map() 可以接受具有多个输入的函数吗?
【发布时间】:2019-06-20 15:27:25
【问题描述】:

我想在按组分层时在多个结果和预测变量上循环 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.

【问题讨论】:

    标签: r function dictionary purrr


    【解决方案1】:

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

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

    这会延迟input_fun 的评估,直到映射实际发生并正确填充. 值。

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-09
      相关资源
      最近更新 更多