2017-04-25 278 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