使用移动平均值或内核平滑来平滑二进制变量

use*_*316 4 r smoothing

我有以下形式的数据:

x      y
0      0
0.01   1
0.03   0
0.04   1
0.04   0
Run Code Online (Sandbox Code Playgroud)

x 从0到1是连续的并且不是等间隔的并且y是二进制的.

我想y用R 来平滑x轴,但是找不到合适的包.我发现的内核平滑函数产生的密度估计值x或将在x的末尾给出错误的估计值,因为它们将在小于0且大于1的区域上进行平均.

我也想避免线性平滑器,如Loess givens然后二进制形式y.我所见的移动平均函数假设等间距x值.

您是否知道任何可以平滑且理想情况下具有带宽选择程序的R功能?我可以写一个移动平均函数和交叉验证来确定带宽,但我更愿意找到一个经过审查的现有函数.

Ben*_*ker 7

我建议使用类似的东西

d <- data.frame(x,y) ## not absolutely necessary but good practice
library(mgcv)
m1 <- gam(y~s(x),family="binomial",data=d)
Run Code Online (Sandbox Code Playgroud)

这将(1)尊重数据的二进制性质(2)使用广义交叉验证自动进行平滑度(术语中的"带宽")选择.

使用

plot(y~x, data=d)
pp <- data.frame(x=seq(0,1,length=101))
pp$y <- predict(m1,newdata=pp,type="response")
with(pp,lines(x,y))
Run Code Online (Sandbox Code Playgroud)

要么

library(ggplot2)
ggplot(d,aes(x,y))+geom_smooth(method="gam",family=binomial)
Run Code Online (Sandbox Code Playgroud)

获得预测/绘制结果.

(我希望你的真实数据集有超过5个观察结果......否则会失败...)