2013-03-27 42 views
2

我在河中使用loess()predict()一些麻煩,我用下面的代碼來模擬數據的黃土線:擬合R中

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

您不能使用'lines'將數據添加到格圖形圖。見'lline()'。您正在繪製數據。如果模型是'x〜PoissonRate(x)',那麼你在'xyplot'中繪製'x〜PoissonRate(x)'。在'llines()'中,你需要給出'x'和'y'參數 - 但是你只能給出'predict()'的輸出,一個向量...... – 2013-03-27 17:43:51

回答

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中的輸入數據不是遞增順序,您也可以獲得可用於線圖的合理預測。例如。

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