在匿名函数内的公式中使用 quosures [英] using quosures within formula inside an anonymous function

查看:44
本文介绍了在匿名函数内的公式中使用 quosures的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 quosures 在自定义函数中传递变量名称以进行数据处理和在公式中使用,但是我在公式中使用 quosures 是不正确的.有没有更好的方法在公式中取消引用参数?

I am trying to use quosures to pass along variable names within a custom function for data processing and use in a formula, but my use of quosures in the formula is not correct. Is there a better way to unquote arguments within a formula?

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

foo <- function(mydata, dv, iv, group_var) {
  dv = enquo(dv)
  iv = enquo(iv)
  group_var = enquo(group_var)

  mydata <- mydata %>% 
    group_by(!!group_var) %>% 
    nest() 

  mydata %>% 
    mutate(model = map(data, 
      ~summary(lm(formula(substitute(dv ~ iv)), data = .))
    )) %>%         
    unnest(model %>% map(tidy))
}

foo(mydata=mtcars, dv=mpg, iv=wt, group_var=cyl)

我的代码产生mutate_impl(.data, dots) 中的错误:评估错误:对象不是矩阵."

My code produces "Error in mutate_impl(.data, dots) : Evaluation error: object is not a matrix."

这是我试图将其变成一个函数的代码的工作版本:

This is a working version of code I am trying to make into a function:

mtcars %>% 
  group_by(cyl) %>% 
  nest() %>% 
  mutate(model = map(data, ~summary(lm(mpg ~ wt, data = .)))) %>% 
  unnest(model %>% map(tidy))

推荐答案

您需要将基本 R 非标准评估与诸如 lm 之类的函数一起使用,这些函数不是在 tidyverse 中"可以这么说的.

You need to use base R nonstandard evaluation with functions like lm which are not "in the tidyverse" so to speak.

因此您可以将内容更改为:

So you could change things to:

foo <- function(mydata, dv, iv, group_var) {
  flma <- as.formula(paste(substitute(dv), "~", substitute(iv)))
  group_var = enquo(group_var)

  mydata <- mydata %>% 
    group_by(!!group_var) %>% 
    nest() 

  mydata %>% 
    mutate(model = map(data, ~summary(lm(flma, data = .)))) %>%         
    unnest(model %>% map(tidy))
}   

foo(mtcars, mpg, wt, cyl)

如果你知道你只是在做简单的回归,那很好.为了获得更大的灵活性,只需直接传递公式,如:

That's fine if you know you are only doing simple regression. For more flexibility just pass the formula directly, as in:

foo2 <- function(mydata, flma, group_var) {
  group_var = enquo(group_var)

  mydata <- mydata %>% 
    group_by(!!group_var) %>% 
    nest() 

  mydata %>% 
    mutate(model = map(data, ~summary(lm(flma, data = .)))) %>%         
    unnest(model %>% map(tidy))
}   

foo(mtcars, mpg ~ wt, cyl)

这篇关于在匿名函数内的公式中使用 quosures的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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