在用户创建的函数中对公式语法使用半引号吗?

问题描述

当我运行此代码时:

# 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 

如何使用准引号使该功能起作用?我认为逻辑与调用library(dplyr)而不是library("dplyr")的逻辑相同。

解决方法

使用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 (包含在rlang 0.5.0中)

blast(list(!!!1:3))
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
#>
#> [[3]]
#> [1] 3

灵活地工作:

asyncSaveUser
,

以下方法应该起作用:

Final_Labels <- data.frame(Stimuli = c("A1.jpg","A2.jpg","A3.jpg","A4.jpg","A5.jpg","H1.jpg"),##note we will need .jpg to be removed to match the files
Duration = c(300,NA,300,60,NA),Start = c(100,1,100,End = c(160,301,160,mean_x = c(.3,.50,.40,mean_y = c(.5,.4,.5,NA))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...