R中的核密度估计器

kernel density estimator in R

我正在使用以下数据的最后一列, Data

我正在尝试将核密度估计器的想法应用于此数据集,该数据集由

其中 k 是一些内核,通常是正态分布,但不一定。h 是带宽,n 是数据集的长度,X_i 是每个数据点,x 是拟合值。所以使用这个等式我有以下代码,

AstroData=read.table(paste0("http://www.stat.cmu.edu/%7Elarry",
                   "/all-of-nonpar/=data/galaxy.dat"),
            header=FALSE)
x=AstroData$V3
xsorted=sort(x)
x_i=xsorted[1:1266]
hist(x_i, nclass=308)
n=length(x_i)
h1=.002
t=seq(min(x_i),max(x_i),0.01)
M=length(t)
fhat1=rep(0,M)
for (i in 1:M){
 fhat1[i]=sum(dnorm((t[i]-x_i)/h1))/(n*h1)}
lines(t, fhat1, lwd=2, col="red")

这会产生以下情节,

这实际上接近我想要的,因为一旦我删除直方图,最终结果应该是这样的,

如果你注意到它被调整得更精细,应该代表密度的红线相当粗糙并且没有缩放得那么高。您看到的最终图是 运行 使用 R 中的密度函数,

plot(density(x=y, bw=.002))

这是我想要达到的目标,而无需使用任何额外的软件包。

谢谢

在与我的室友交谈后,他给了我继续前进并减少 t-values (x) 间隔的想法。在做一些事情时,我将它从 0.01 更改为 0.001。因此,该图的最终代码如下所示,

AstroData=read.table(paste0("http://www.stat.cmu.edu/%7Elarry",
               "/all-of-nonpar/=data/galaxy.dat"),
        header=FALSE)
x=AstroData$V3
xsorted=sort(x)
x_i=xsorted[1:1266]
hist(x_i, nclass=308)
n=length(x_i)
h1=.002
t=seq(min(x_i),max(x_i),0.001)
M=length(t)
fhat1=rep(0,M)
for (i in 1:M){
fhat1[i]=sum(dnorm((t[i]-x_i)/h1))/(n*h1)}
lines(t, fhat1, lwd=2, col="blue")

下面的剧情就是我想要的,