[R] help with predict and plotting confidence intervals
David Winsemius
dwinsemius at comcast.net
Thu Mar 12 16:45:15 CET 2009
On Mar 12, 2009, at 11:14 AM, Michael Denslow wrote:
>
> Dear R help,
>
> This seems to be a commonly asked question and I am able to run
> examples that have been proposed, but I can't seems to get this to
> work with my own data. Reproducible code is below. Thank you in
> advance for any help you can provide.
It is commonly asked ... and commonly answered.
>
>
> The main problem is that I can not get the confidence lines to plot
> correctly.
> The secondary problem is that predict is not able to find my object
> when
> I include a model object.
>
> ## THE DATA
> wt.data <- data.frame(code = factor(LETTERS[1:24]),
> area =
> c(60865,480,656792,92298,1200,1490,8202,4000,220,245,4000,390,325,
> 16,162911,20235,68800,3389,7,696,4050,1498,1214,99460),
> species =
> c(673,650,1353,1026,549,536,782,734,516,580,673,560,641,443,1105,
> 871,789,575,216,407,942,655,582,1018))
>
> # TRANSFORM AND ADD TO DATAFRAME
> wt.data$logA <- log10(wt.data$area)
> wt.data$logS <- log10(wt.data$species)
>
> wt.mod <- lm(logS~logA, data = wt.data)
>
> # PLOT THE DATA
> with(wt.data,plot(logA,logS, ylim = c(2.3,3.2),xlim = c(0,6)))
> abline(wt.mod, lwd = 2)
>
>
> # create a prediction dataframe the same length as data
> pred.frame <- data.frame(a = seq(0,6, length.out = 24))
>
> # error ' object "logA" not found'
I suspect you omitted the actual call that produced this error. I
suspect it was something along the lines of:
> predwt <- predict(wt.mod, newdata=pred.frame)
Error in eval(expr, envir, enclos) : object "logA" not found
>
> # I am not sure why object is not found, I assume this has to do with
> # the way I added the transformed variables to the dataframe
Because you didn't give the arguments the same name(s) as were used in
the model formula.
>
> pp <- predict(wt.mod, int = "p", newdata=pred.frame)
>
> # runs ok?
> pp <- predict(lm(wt.data$logS~wt.data$logA), int = "p",
> newdata=pred.frame)
>
> # lines are jagged??
Lines? What lines? If predict does not find a newdata object that
satisfies its requirements, it uses the original data.
>
> # I am not sure how to get the lines to draw correctly here
> matlines(pred.frame$a,pp, lty=c(1,2,2),col="black")
>
The x values are your sequence whereas the y values are in the
sequence from the original data. They are not correctly associated
with each other.
Try:
pp <- predict(lm(wt.data$logS~wt.data$logA), int = "p", newdata=
data.frame(logA=seq(0,6, length.out = 24)) )
plot(pp)
--
david winsemius
More information about the R-help
mailing list