我已經在這裏做了相當數量的閱讀,並瞭解到我應該避免操縱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)
並且具有carat_color *清晰度的aov結果。提前致謝。
解決方案
這是基於@亞倫的評論一個工作版本,這表明發生了什麼:
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))
}
感謝您看這個@slammaster我想我可能已經與'更新同樣的問題。公式'裏面的功能!對於調用的格子部分,我必須讓groups參數成爲數據框中某個事物的未加引號的名稱,所以我不能使用'dat $ clarity',我只能使用'clarity'作爲參數。因此,在追加組之後,lm或aov呼叫必須以相同的方式工作。 – 2013-02-12 19:25:03
嘗試更新一個字符串(格式不好,因爲在評論中,對不起......):tf < - function(formula,group,d){
Aaron
2013-02-12 19:31:59
@Aaron:應該發佈爲答案。 – 2013-02-12 19:35:58