2

私は SO でかなりの量の読書をして、一般的にformula objectsas 文字列の操作を避けるべきであることを学びましたが、安全な方法でこれを行う方法をまだ見つけていません:

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
}

おそらく、私が最も近かったのは使用することでしたが、それは RHSreformulateのみを提供し、 . 次のような関数を使用したい:+*

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))
}
4

2 に答える 2

3

update.formula で問題を解決できると思いますが、関数呼び出し内での更新に問題がありました。以下にコーディングしたとおりに機能しますが、変数名ではなくグループに列を渡していることに注意してください。次に、その列を関数データセットに追加してから、作業を更新します。

また、2 番目の式で必要なことが正確に行われているかどうかもわかりませんが、update.formula のヘルプ ファイルを見て、少しいじってみてください。

http://stat.ethz.ch/R-manual/R-devel/library/stats/html/update.formula.html

tf <- function(formula,groups,d){
  d$groups=groups
  newForm = update(formula,~.*groups)
  mod = lm(newForm,data=d)
}

dat  = data.frame(carat=rnorm(10,0,1),color=rnorm(10,0,1),color2=rnorm(10,0,1),clarity=rnorm(10,0,1))
m = tf(carat~color,dat$clarity,d=dat)
m2 = tf(carat~color+color2,dat$clarity,d=dat)

tf2 <- function(formula, group, d) {
  f <- paste(".~.*", deparse(substitute(group)))
  newForm <- update.formula(formula, f)
  lm(newForm, data=d)
}
mA = tf2(carat~color,clarity,d=dat)
m2A = tf2(carat~color+color2,clarity,d=dat)

編集: @Aaron が指摘したように、それは私の問題を解決するものです:コード例により良いオプションとして追加deparseしたので、両方がどのように機能するかを確認できます。substitutetf2

于 2013-02-12T19:17:23.180 に答える
0

関数内の関数のスコープと呼び出しに問題がある場合に使用する 1 つの手法は、パラメーターを文字列として渡し、それらの文字列から関数内の呼び出しを構築することです。これは、ここでどのように見えるかです。

tf <- function(formula, data, groups) {
  f <- paste(".~.*", groups)
  m <- eval(call("aov", update.formula(as.formula(formula), f), data = as.name(data)))
  summary(m)
}

tf("mpg~vs", "mtcars", "am") 

この別の例については、以前の質問の 1 つに対するこの回答を参照してください: https://stackoverflow.com/a/7668846/210673

この質問の姉妹の質問に対するこの回答も参照してください。ここでは、 https xyplot: //stackoverflow.com/a/14858661/210673

于 2013-02-13T16:48:39.950 に答える