我有两个向量:1)~1000个样本均值和2)相应的~1000个标准偏差。我想创建这些数据的核密度图,使用样本均值作为估算密度的观测值,并将每个均值的标准偏差作为每次观测的带宽。问题是,密度仅允许长度为1的向量用作带宽。例如:
plot(density(means,bw=error))
返回以下警告:
1: In if (!is.finite(bw)) stop("non-finite 'bw'") :
the condition has length > 1 and only the first element will be used
2: In if (bw <= 0) stop("'bw' is not positive.") :
the condition has length > 1 and only the first element will be used
3: In if (!is.finite(from)) stop("non-finite 'from'") :
the condition has length > 1 and only the first element will be used
4: In if (!is.finite(to)) stop("non-finite 'to'") :
the condition has length > 1 and only the first element will be used
...我得到的图表使用列表中第一项的错误作为我所有观察的带宽。
关于如何为每个用于生成核密度图的观察实现单独的用户定义带宽的任何想法?
答案 0 :(得分:0)
看起来density
不支持这种带宽规范。
mydensity <- function(means, sds) {
x <- seq(min(means - 3*sds), max(means + 3*sds), length.out=512)
y <- sapply(x, function(v) mean(dnorm(v, means, sds)))
cbind(x, y)
}
这将比真实函数(在计算中似乎使用fft)慢得多。它在工作中,左边是小带宽,右边是大带:
set.seed(144)
means <- runif(1000)
sds <- ifelse(means < 0.5, 0.001, 0.05)
plot(mydensity(means, sds))