也许你想要
match.arg
. 例如:
lmfun <- function(df, yname, xname){
y <- match.arg(deparse(substitute(yname)), names(df))
x <- match.arg(deparse(substitute(xname)), names(df))
f <- as.formula(paste0(y, "~", x))
lm.fit <- do.call("lm", list(data = quote(df), f))
coef(lm.fit)
}
lmfun(mtcars, yname = mp, dis)
# (Intercept) disp
# 29.59985476 -0.04121512
lmfun(mtcars, yname = mp, d)
# Error in match.arg(deparse(substitute(xname)), names(df)) :
# 'arg' should be one of âmpgâ, âcylâ, âdispâ, âhpâ, âdratâ, âwtâ, âqsecâ,
# âvsâ, âamâ, âgearâ, âcarbâ
这一次,它没有发挥应有的作用
d
disp
或
drat
.