【发布时间】:2019-03-22 05:47:14
【问题描述】:
考虑以下函数:
lm_eqn <- function(df, indep, dep){
lm(formula = dep ~ indep, data = df)
}
lm_eqn(iris, Sepal.Length, Sepal.Width) ## does not work, throws error.
我尝试以多种方式引用/取消引用。这些都没有成功,抛出不同的错误,而且对我没有任何帮助:
使用deparse(substitute(dep))
contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) 中的错误: 对比只能应用于具有 2 个或更多级别的因素
使用quo(dep) 或enquo(dep) 或expr(dep)
model.frame.default(formula = dep ~ indep, data = df, drop.unused.levels = TRUE) 中的错误:对象不是矩阵
在上面使用 !! 取消引用:
!dep 中的错误:参数类型无效
在函数体内为公式指定变量名有效:
lm_eqn2 <- function(df){
lm(formula = Sepal.Length ~ Sepal.Width, data = df)
}
lm_eqn2(iris)
# Call:
# lm(formula = Sepal.Length ~ Sepal.Width, data = df)
# Coefficients:
# (Intercept) Sepal.Width
# 6.5262 -0.2234
我错过了什么?
【问题讨论】:
标签: r