I'm having some trouble using loess()
and predict()
in R. I have used the following code to simulate data:
Overall=0.6
RR=1.1
Noise=0.05
x=seq(from=0.01, to=10, by=0.01)
logRR=log(RR)
logBeta0=log(Overall)
linear.pred = logBeta0 + (logRR*x) + rnorm(length(x), 0, Noise*sqrt(x))
linear.pred.high = logBeta0 + (logRR*15) + rnorm(length(x), 0, Noise/5)
PoissonRate <- function (x) ifelse(x<=9, exp(linear.pred), exp(linear.pred.high))
xyplot(PoissonRate(x)~x) #the shape of the 'raw' data
loess_fit <- loess(x~PoissonRate(x))
lines(predict(loess_fit), col = "black")
Apologies but I can't work out how to attach a picture to show what this looks like!
The last two lines of code end up just adding a random black line half off the graph, although when I have used this command on different (very similar) data before, it has seemed to work fine. What am I missing?! Any help would be great, thanks :)
You shouldn't call llines()
(if that is what you meant by lines()
) outside of the xyplot
call, at least to my understanding. ?llines
has:
Description:
These functions are intended to replace common low level
traditional graphics functions, primarily for use in panel
functions.
Hence, one option is to do as it suggests and build your own panel function on the fly. Here is an example:
set.seed(1)
dat <- data.frame(pr = PoissonRate(x), x = x)
loess_fit <- loess(pr ~ x, data = dat)
xyplot(PoissonRate(x) ~ x,
panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
llines(dat$x, predict(loess_fit), col.line = "red")
})
which produces:
In general, I would probably do this a different way - I would generate the data outside the formula. The I would predict
for new data locations spread evenly and in order over the range of x
. That way, even if the input data are not in increasing order in x
you get sensible predictions you can use for a line plot. Eg
## following on from the above
pred <- with(dat, data.frame(x = seq(min(x), max(x), length = 100)))
pred <- transform(pred, pr = predict(loess_fit, newdata = x))
xyplot(PoissonRate(x) ~ x,
panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
with(pred, llines(x, pr, col.line = "red"))
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.