0

当我运行此代码时:

# Create example data
df <- tibble(age=rnorm(10),
         income=rnorm(10))

make_model <- function(response_var, df){
  
  # Create formula
  form <- as.formula(response_var ~ .)
  
  # Create model
  model <- lm(form , data=df)
  
  # Return coefficients
  return(coef(model))
}

make_model(income, df)

我收到以下错误

 Error in eval(predvars, data, env) : object 'income' not found 

如何使用 quasiquotation 使此功能起作用?我假设逻辑与我们如何调用library(dplyr)而不是library("dplyr").

4

2 回答 2

2

使用blast()(将包含在 rlang 0.5.0 中)

blast <- function(expr, env = caller_env()) {
  eval_bare(enexpr(expr), env)
}

make_model <- function(data, column) {
  f <- blast(!!enexpr(column) ~ .)
  model <- lm(f, data = data)
  coef(model)
}

df <- data.frame(
  age = rnorm(10),
  income = rnorm(10)
)
make_model(df, income)
#> (Intercept)         age
#>  -0.3563103  -0.2200773

工作灵活:

blast(list(!!!1:3))
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
#>
#> [[3]]
#> [1] 3
于 2020-10-29T18:22:57.407 回答
0

以下应该有效:

library(tidyverse)

# Your original function, modified
make_model <- function(df, column) {
  column <- enexpr(column)
  form <- as.formula(paste0(quo_text(column), " ~ ."))

  model <- lm(form, data = df)

  return(coef(model))
}

# Your original data and call
tibble(
    age = rnorm(10),
    income = rnorm(10)
  ) %>% 
  make_model(income)
于 2020-10-29T17:45:01.050 回答