首页 > 解决方案 > 如何将公式作为字符串传递?

问题描述

我想将字符串作为aov函数中的公式传递

这是我的代码

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

我的目标是输出与此相同

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

标签: r

解决方案


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

下面,do.call确保formula(formula)在发送到之前对其进行评估,aov以便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

推荐阅读