R中的核密度估计器

问题描述

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

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

Equation setup for kernal density

其中,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")

产生以下情节,

Resulting plot

实际上接近于我想要的结果,因为一旦删除直方图,最终结果应显示为:

Final plot

如果您注意到微调,并且应该代表密度的红线相当粗糙,并且缩放比例不高。您看到的最终图是使用R中的密度函数运行的

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

在不使用任何其他软件包的情况下,我想了解的是什么。

谢谢

解决方法

与我的室友交谈后,他给了我继续降低t值(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")

用以下术语表示,这是我想要的图,

Correct plot

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...