我已经在 SO 上进行了大量阅读,并了解到我通常应该避免操作formula objects
as 字符串,但我还没有完全找到如何以安全的方式做到这一点:
tf <- function(formula = NULL, data = NULL, groups = NULL, ...) {
# Arguments are unquoted and in the typical form for lm etc
# Do some plotting with lattice using formula & groups (works, not shown)
# Append 'groups' to 'formula':
# Change y ~ x as passed in argument 'formula' to
# y ~ x * gr where gr is the argument 'groups' with
# scoping so it will be understood by aov
new_formula <- y ~ x * gr
# Now do some anova (could do if formula were right)
model <- aov(formula = new_formula, data = data)
# And print the aov table on the plot (can do)
print(summary(model)) # this will do for testing
}
也许我来的最接近的是使用reformulate
,但这仅提供+
RHS,而不是*
. 我想使用这样的功能:
p <- tf(carat ~ color, groups = clarity, data = diamonds)
并获得克拉 ~ 颜色 * 净度的 aov 结果。提前致谢。
解决方案
这是基于@Aaron 的评论的工作版本,它演示了正在发生的事情:
tf <- function(formula = NULL, data = NULL, groups = NULL, ...) {
print(deparse(substitute(groups)))
f <- paste(".~.*", deparse(substitute(groups)))
new_formula <- update.formula(formula, f)
print(new_formula)
model <- aov(formula = new_formula, data = data)
print(summary(model))
}