2017-04-25 277 views
-2

我有以下數據:如何計算平滑曲線的斜率中的R

enter image description here

我繪製該數據的點,然後使用下面的代碼平滑它在圖上:

scatter.smooth(x=1:length(Ticker$ROIC[!is.na(Ticker$ROIC)]), 
    y=Ticker$ROIC[!is.na(Ticker$ROIC)],col = "#AAAAAA", 
    ylab = "ROIC Values", xlab = "Quarters since Feb 29th 2012 till Dec 31st 2016") 

enter image description here

現在我想找到這個平滑曲線的逐點的斜率。也適合平滑圖形的趨勢線。我怎樣才能做到這一點?

+0

yes,point-wise slope @李哲源ZheyuanLi – ForeverLearner

+0

@李哲源ZheyuanLi謝謝!是啊黃土曲線功能的問題和我的數據是我有負數。我會嘗試你所建議的。 – ForeverLearner

回答

1
#DATA 
set.seed(42) 
x = rnorm(20) 
y = rnorm(20) 

#Plot the points 
plot(x, y, type = "p") 

#Obtain points for the smooth curve 
temp = loess.smooth(x, y, evaluation = 50) #Use higher evaluation for more points 

#Plot smooth curve 
lines(temp$x, temp$y, lwd = 2) 

#Obtain slope of the smooth curve 
slopes = diff(temp$y)/diff(temp$x) 

#Add a trend line 
abline(lm(y~x)) 
+0

@ d.b感謝您的解決方案,但由於我的數據有負數,我無法使用'黃土'。負數的日誌未定義,並引發錯誤。 – ForeverLearner

+0

@ForeverLearner什麼是阻止你抵消這些價值/正常化... – snb

2

有一些有趣的R包實現非參數導數估計。紐厄爾和艾貝克的短審查可以是有幫助的:http://maths.dur.ac.uk/~dma0je/Papers/newell_einbeck_iwsm07.pdf

在這裏,我們考慮基於所述pspline軟件包(在m階導數平滑用懲罰花鍵)的示例:

數據生成過程是一個負邏輯模型與加性噪聲(因此y值都是負像@ForeverLearner的ROIC變量:

set.seed(1234) 
x <- sort(runif(200, min=-5, max=5)) 
y = -1/(1+exp(-x))-1+0.1*rnorm(200) 

我們開始繪製曲線的非參數估計(黑線是真正的曲線和紅色估計曲線):

library(pspline) 
pspl <- smooth.Pspline(x, y, df=5, method=3) 
f0 <- predict(pspl, x, nderiv=0) 

enter image description here

然後,我們估計曲線的一階導數:

f1 <- predict(pspl, x, nderiv=1) 
curve(-exp(-x)/(1+exp(-x))^2,-5,5, lwd=2, ylim=c(-.3,0)) 
lines(x, f1, lwd=3, lty=2, col="red") 

enter image description here

而這裏的二階導數:

f2 <- predict(pspl, x, nderiv=2) 
curve((exp(-x))/(1+exp(-x))^2-2*exp(-2*x)/(1+exp(-x))^3, -5, 5, 
     lwd=2, ylim=c(-.15,.15), ylab=) 
lines(x, f2, lwd=3, lty=2, col="red") 

enter image description here

+0

謝謝@Marco桑德里這是非常有益的! – ForeverLearner