【发布时间】:2013-02-12 18:53:38
【问题描述】:
我在这里阅读了大量关于 SO 的内容,并了解到我通常应该避免将 formula objects 作为字符串进行操作,但我还没有完全找到如何以安全的方式执行此操作:
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))
}
【问题讨论】: