在R中拟合黄土线

时间:2013-03-27 17:37:30

标签: r simulation predict loess

我在使用R中的loess()predict()时遇到了一些问题。我使用以下代码来模拟数据:

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")

道歉,但我无法弄清楚如何附上图片来展示它的样子!

最后两行代码最终只是在图形上添加了一条随机黑线,尽管我之前在不同(非常相似)的数据上使用过此命令时,它似乎工作正常。我错过了什么?!任何帮助都会很棒,谢谢:)。

1 个答案:

答案 0 :(得分:1)

至少根据我的理解,你不应该在llines()电话之外致电lines()(如果这就是xyplot的意思)。 ?llines有:

Description:

     These functions are intended to replace common low level
     traditional graphics functions, primarily for use in panel
     functions.

因此,一个选项是按照它的建议去做,并动态构建自己的面板功能。这是一个例子:

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")
  })

产生:

enter image description here

一般来说,我可能会采用不同的方式 - 我会在公式之外生成数据。我希望predict新数据位置在x范围内均匀分布。这样,即使输入数据在x中不是递增的顺序,您也可以获得合理的预测,您可以将其用于线图。 E.g。

## 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"))
  })
相关问题