# [R-sig-eco] Predict with 2 factors in an additive model

Gavin Simpson gavin.simpson at ucl.ac.uk
Sat Oct 15 11:06:11 CEST 2011

```On Fri, 2011-10-14 at 17:09 -0600, Manuel Spínola wrote:
> Dear list members,
>
> I have an additive linear model (see below fro a reproducible example) and I
> want to use the function "predict" to have the value of the response
> variable for each level of factor f1 and each level of factor f2 in the
> additive model (not interaction). When I did predict I only get 2 values.

Because there are only two rows in `newdata`! If you want f1-a with f2-a
and f1-a with f2-b, and f1-b with f2-a and f1-b with f2-b, that
necessitates four rows in `newdata` to contain the combinations.

G

> y=rnorm(40,1,1)
>
> f1=c(rep("a",20),rep("b",20))
> f2=c(rep("a",10),rep("b",10),rep("a",10),rep("b",10))
>
> data=data.frame(y,f1,f2)
>
> mod1 = lm(y ~ f1 + f2, data=data)
>
> summary(mod1)
>
> newData = data.frame(f1 = factor(c("a", "b")), f2 = factor(c("b", "a")))
>
> > predict(mod1, newdata = newData, appendData  =  TRUE)
>         1         2
> 1.0460148 0.9468983
>
> Thank you very much in advance.
>
> Best,
>
> Manuel
>
> _______________________________________________
> R-sig-ecology mailing list
> R-sig-ecology at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-ecology

--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

```