簡體   English   中英

為什么替代公式對lm和oneway.test有效,但對aov不起作用?

[英]Why does a substituted formula work for lm and oneway.test, but not aov?

 example <- data.frame(
   var1 = c(1, 2, 3, 4, 5, 6, 7, 8),
   class = c(rep(1, 4), rep(2, 4))
 )
 example$class <- as.factor(example$class)

這個問題提供了一個解決方法,可以使用alternate和as.name為aov創建公式,但是我不明白為什么該公式適用於oneway.testlm 有人可以解釋嗎?

 fm <- substitute(i ~ class, list(i = as.name('var1')))
 oneway.test(fm, example)

    One-way analysis of means (not assuming equal variances)

data:  var1 and class
F = 19.2, num df = 1, denom df = 6, p-value = 0.004659

 lm(fm, example)

Call:
lm(formula = fm, data = example)

Coefficients:
(Intercept)       class2  
        2.5          4.0  

 aov(fm, example)
Error in terms.default(formula, "Error", data = data) : 
  no terms component nor attribute

問題在於substitute者返回的是未評估的調用,而不是公式。 相比

class(substitute(a~b))
# [1] "call"
class(a~b)
# [1] "formula"

如果您對它進行了評估(就像在其他答案中所做的那樣),那么兩者都將起作用

fm <- eval(substitute(i ~ class, list(i = as.name('var1'))))
oneway.test(fm, example)
aov(fm, example)

您收到的錯誤消息來自aov()調用的terms函數。 此函數需要對公式而不是調用進行操作。 基本上這就是發生的事情

# ok
terms(a~b)

# doesn't work
unf <- quote(a~b)  #same as substitute(a~b)
terms(unf)
# Error in terms.default(unf) : no terms component nor attribute

# ok
terms(eval(unf))

造成這種差異的一個可能原因是, fm實際上是一個call而不是formula並且顯然某些函數進行了轉換,而其他函數則沒有。

如果您這樣做:

fm <- as.formula(fm)

然后,撥打aov的電話將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM