|
R语言中density函数中kernel参数所对应的核函数视乎都具有拖尾,一下为box核的概率密度估算代码。
density_box=function(entity,bandwidth)
{
if (missing(bandwidth)) {
bandwidth=density(entity)$bw
}
min_x=min(entity)
max_x=max(entity)
x=seq(min_x, max_x,length.out=1000)
y=rep(0, length(x))
box=function(entity){
for (i in 1:length(x)) {
if (abs(x[i] - entity) <= bandwidth/2) {
y[i] <<- y[i] + 1
}
}
}
for(i in 1:length(entity))
{
box(entity[i])
}
y=y/length(entity)
result=cbind(x,y)
colnames(result)=c("scale","density")
result
}
y=density_box(entity)
par(mfrow = c(2, 1))
plot(y,type="l")
plot(density(entity))
以下为效果图,上图为box核,下图为高斯核
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-9-27 10:34
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社