Hi:
There are a couple of things here. Firstly, if you intend to predict from a
model in R, make sure your input to the model is a data frame. You can fit a
model piecemeal with a set of vectors, but there's a distinct possibility
you'll end up frustrated when trying to make predictions with new data.
I'm
not going to get into the details of the problem, but I will say that if you
input a data frame, prediction on new observations is likely to go more
smoothly since these must be entered as a data frame with a column for each
term on the right hand side of the model formula to which it associates.
Start with this instead:
d1 <- data.frame(sl, yd, sex)
m <- lm(sl ~ yd * sex, data = d1)
Your prediction data frame has to have columns for both yd and sex, since
those are the two explanatory variables on the right hand side of your model
formula. If you want predictions at your values of yd for each sex, then
yd <- 4:8
dfp <- data.frame(yd = rep(yd, 2), sex = rep(c('female',
'male'), each length(yd)))
cbind(dfp, yhat = predict(m, newdata = dfp))
yd sex yhat
1 4 female 5
2 5 female 6
3 6 female 7
4 7 female 8
5 8 female 9
6 4 male 5
7 5 male 6
8 6 male 7
9 7 male 8
10 8 male 9
[The predictions are the same for each gender because the main effect for
sex is 0, as is the interaction between yd and sex.]
HTH,
Dennis
On Thu, Feb 10, 2011 at 8:28 AM, Zhao Jin <jindichocking@gmail.com> wrote:
> Hi,
>
>
>
> I don't know how to make prediction with a factor in the linear model.
>
> Say
>
> yd=c(1,2,3,4,5)
>
> > sl=c(2,3,4,5,6)
>
> >
sex=c("male","male","female","female","male")
>
> > sex=factor(sex)
>
> > m=lm(sl~yd+sex+sex:yd)
>
>
>
> How to make a prediction with new data like yd=c(4,5,6,7,8) for male and
> female separately ?
>
>
>
> Thank you very much.
>
>
>
> Zhao Jin
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]