【问题标题】:How to pass a formula as a string?如何将公式作为字符串传递?
【发布时间】:2020-10-25 21:44:42
【问题描述】:

我想在aov 函数中传递一个字符串作为公式

这是我的代码

      library(fpp)
      
      formula <-
        "score ~ single"
      
      aov(
        formula, 
        credit[c("single", "score")]   
      )
      

我的目标是输出和这个一样

aov(score ~ single,
        credit[c("single", "score")])

【问题讨论】:

  • formula &lt;- as.formula("score ~ single")
  • 我相信 aov(as.formula( formula ) 也应该可以工作(因此将其转换为 aov() 函数中的公式)。
  • 小心这个。公式有两部分:可见部分(例如score ~ single)和附加环境(如果lm() 等函数不在data 参数中,它们将去寻找变量)。确保无论你想要做什么,这两个部分都是正确的。

标签: r


【解决方案1】:

这个问题似乎非常接近How to pass string formula to R's lm and see the formula in the summary?,除了那个问题涉及lm

下面,do.call 确保在发送到 aov 之前评估 formula(formula),以便输出中的 Call: 行正确显示;否则,它会直接显示formula(formula)do.call 不仅评估公式,还会评估 credit 将其扩展为显示其所有值的巨大输出,而不是单词 credit,所以我们 quote 它来防止这种情况。如果您不关心 Call: 行的样子,可以将其缩短为 aov(formula(formula), credit)

do.call("aov", list(formula(formula), quote(credit)))

给予:

Call:
   aov(formula = score ~ single, data = credit)

Terms:
                  single Residuals
Sum of Squares    834.84  95658.64
Deg. of Freedom        1       498

Residual standard error: 13.8595
Estimated effects may be unbalanced

【讨论】:

    【解决方案2】:

    您可以使用reformulate 即时创建公式。

    response <- 'score'
    pred <- 'single'
    aov(reformulate(pred, response), credit[c("single", "score")])
    
    #Call:
    #   aov(formula = score ~ single, data = credit[c("single", "score")])
    
    #Terms:
    #                  single Residuals
    #Sum of Squares    834.84  95658.64
    #Deg. of Freedom        1       498
    
    #Residual standard error: 13.8595
    #Estimated effects may be unbalanced
    

    【讨论】:

      猜你喜欢
      • 2010-11-04
      • 2019-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多