R - 黄土曲线未通过点正确拟合

时间:2017-03-17 17:57:48

标签: r regression curve loess

我试图过滤掉过于接近或低于黄土曲线的点:

结果如下所示:Scatterplot with loess curve

显然不是理想的结果。

但是,如果我使用scatter.smooth函数,我会得到一条正确的曲线: Scatterplot with scatter.smooth curve

如何通过我的数据正确拟合黄土曲线?

1 个答案:

答案 0 :(得分:2)

主要是,我们应该检查predict函数返回的内容:

head(predict(afit))
[1] 0.8548271 0.8797704 0.8584954 0.8031563 0.9012096 0.8955874

它是一个矢量,所以当我们将它传递给lines时,R说,"好吧,你没有指定x值,所以我&#39 ; ll只使用x值的索引" (尝试plot(2:10)看看我的意思。)

所以,我们需要做的是指定一个2列矩阵传递给lines,而不是:

cbind(sort(means), predict(afit, newdata = sort(means)))

应该做的伎俩。您的功能可以写成:

FilterByVariance<-function(dat, threshold = 0.90, span = 0.75){
means <- apply(dat,1,mean) 
sds <- apply(dat,1,sd) 
cv <- sqrt(sds/means)

afit<-loess(cv~means, span = span)
resids<-afit$residuals
# good<-which(resids >= quantile(resids, probs = threshold)) 
# points above the curve will have a residual > 0
good <- which(resids > 0)
#plots

plot(cv~means)
lines(cbind(sort(means), predict(afit, newdata = sort(means))), 
      col="blue",lwd=3)
points(means[good],cv[good],col="red",pch=19)

}
相关问题