使用多个点而不是随机采样来插值密度

Interpolate density using a number of points instead of random sampling

当 R 计算密度 (x) 时,它使用 n = 512(我相信),因此它随机尝试选择 512 个点并使用这些点插入密度函数。我有一个点列表 (p),我想在计算密度 (x) 时使用它,而不是随机抽样 512 个点。 (忽略这可能导致的任何并发症、有效性等——我只是在寻找一种方法来实现它)

  1. 有没有办法修改 density(x) 以便我可以传递一个列表 点而不是使用随机抽样?
  2. density(x) 使用的算法是什么?
  3. 我应该使用其他功能吗?

所以经过一些研究,你可以计算内核密度估计如下(来自Wikipedia):

#` Data
set.seed(1)                                                     #Used for reproducibility
data = c(rnorm(100,-10,1),rnorm(100,10,1))                      #Two Normals mixed

#` True
phi = function(x) exp(-.5*x^2)/sqrt(2*pi)                       #Normal Density
tpdf = function(x) phi(x+10)/2+phi(x-10)/2                      #True Density

#` Kernel
h = sd(data)*(4/3/length(data))^(1/5)                           #Bandwidth estimated by Silverman's Rule of Thumb
Kernel2 = function(x) mean(phi((x-data)/h)/h)                   #Kernel Density
kpdf = function(x) sapply(x,Kernel2)                            #Elementwise application

#` Plot
x=seq(-25,25,length=1000)                                       #Linear Space
plot(x,tpdf(x),type="l",ylim=c(0,0.23),col="red")               #Plot True Density
par(new=T)
plot(x,kpdf(x),type="l",ylim=c(0,0.23),xlab="",ylab="",axes=F)  #Plot Kernel Density with Silverman's Rule of Thumb

请注意,我可以 select x 以我想要的任何方式