user106014
user106014

Reputation: 41

How to pass a formula as a string?

I'd like to pass a string as the formula in the aov function

This is my code

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

My goal is for the output to be the same as this

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

Upvotes: 1

Views: 761

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388962

You can use reformulate to create the formula on the fly.

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

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 269501

This question seems very close to How to pass string formula to R's lm and see the formula in the summary? except that question involves lm.

Below, do.call ensures that formula(formula) is evaluated before being sent to aov so that the Call: line in the output shows properly; otherwise, it would literally show formula(formula). do.call not only evaluates the formula but would also evaluate credit expanding it into a huge output showing all its values rather than the word credit so we quote it to prevent that. If you don't care what the Call: line looks like it could be shortened to aov(formula(formula), credit) .

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

giving:

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

Upvotes: 4

Related Questions