[R] Building a formula using paste

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Fri Feb 1 11:03:32 CET 2008


Bill.Venables at csiro.au wrote:
> use as.formula() rather than just formula(). 
>
>
>   
Hm?

That doesn't seem to cut it for me:

> f <- as.formula(y~x)
> lm(f)

Call:
lm(formula = f)

Coefficients:
(Intercept)            x
    0.06437     -0.09714

> summary(lm(f))

Call:
lm(formula = f)

Residuals:
    Min      1Q  Median      3Q     Max
-1.2780 -0.4229 -0.3208  0.7534  1.3073

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.06437    0.61961   0.104    0.920
x           -0.09714    0.09986  -0.973    0.359

Residual standard error: 0.907 on 8 degrees of freedom
Multiple R-Squared: 0.1058,     Adjusted R-squared: -0.005995
F-statistic: 0.9464 on 1 and 8 DF,  p-value: 0.3591

<etc.>

The problem is that we get the call and not the formula, and this
appears to be the case whether you use formula or as.formula. Also

> identical(as.formula(y~x), formula(y~x))
[1] TRUE

I see two workarounds:

(a) Extract the formula explicitly and print it along with the output

> formula(m)
y ~ x
> m

Call:
lm(formula = f)

Coefficients:
(Intercept)            x
    0.06437     -0.09714

(b) substitution tricks, e.g.

> eval(bquote(lm(.(f))))

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x
    0.06437     -0.09714


>
> Hi All
>
> I have looked but cannot find an answer to this.
>
> I want to build a formula dynamically (in a function), using for example
> paste, and using it in a model:
>
> 	fr<-"F1"	
>   	f1<-formula(paste(fr, "~ SensoryTerm"))
>   	m1<-aov(f1, data=vdata)
>
> So this is the equivalent of m1<-aov(F1 ~ SensoryTerm, data=vdata)
>
> This works fine but the problem is the formula appears as "f1" in the
> summary(m1) of the model and not "F1 ~ SensoryTerm". With many models
> this can be a bit confusing ....
>
> Is there a way to code this so the formula appears in the model summary?
>
>   
>   


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list