[英]how to calculate the slope of a smoothed curve in R
I have the following data:我有以下数据:
I plotted the points of that data and then smoothed it on the plot using the following code :我绘制了该数据的点,然后使用以下代码在图上对其进行平滑处理:
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")
Now I want to find the Point-wise slope of this smoothed curve.现在我想找到这条平滑曲线的逐点斜率。 Also fit a trend line to the smoothed graph.
还将趋势线拟合到平滑图上。 How can I do that?
我怎样才能做到这一点?
There are some interesting R packages that implement nonparametric derivative estimation.有一些有趣的 R 包可以实现非参数导数估计。 The short review of Newell and Einbeck can be helpful:http://maths.dur.ac.uk/~dma0je/Papers/newell_einbeck_iwsm07.pdf
Newell 和 Einbeck 的简短评论可能会有所帮助:http ://maths.dur.ac.uk/~dma0je/Papers/newell_einbeck_iwsm07.pdf
Here we consider an example based on the pspline
package (smoothing splines with penalties on order m derivatives):这里我们考虑一个基于
pspline
包的例子(平滑样条,对 m 阶导数进行惩罚):
The data generating process is a negative logistic models with an additive noise (hence y values are all negative like the ROIC variable of @ForeverLearner) :数据生成过程是一个带有加性噪声的负逻辑模型(因此 y 值都是负的,就像@ForeverLearner 的 ROIC 变量一样):
set.seed(1234)
x <- sort(runif(200, min=-5, max=5))
y = -1/(1+exp(-x))-1+0.1*rnorm(200)
We start plotting the nonparametric estimation of the curve (the black line is the true curve and the red one the estimated curve):我们开始绘制曲线的非参数估计(黑线是真实曲线,红线是估计曲线):
library(pspline)
pspl <- smooth.Pspline(x, y, df=5, method=3)
f0 <- predict(pspl, x, nderiv=0)
Then, we estimate the first derivative of the curve:然后,我们估计曲线的一阶导数:
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")
And here the second derivative:这里是二阶导数:
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")
#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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.