[英]Unable to produce values of a kernel density estimator in R
I'm simulating random numbers from the exponential distribution with rate=1. 我正在从rate = 1的指数分布中模拟随机数。 I have plotted a kernel density of the data using the density() function in R. What I want is a function f that gives me the value of the density at any point. 我已经使用R中的density()函数绘制了数据的内核密度。我想要的是一个函数f,该函数可以在任意点提供密度值。 I have tried the following code: 我尝试了以下代码:
n=10^5
x=rexp(n,rate=1)
d=density(x,kernel="gaussian")
f=function(x){d$y[x]}
f(1)
plot(d)
However, f(1) clearly does not match the value of the density function at the point x=1. 但是,f(1)显然与x = 1点处的密度函数值不匹配。 Where am I going wrong? 我要去哪里错了?
density
produces a list which contains, in field x
, the coordinates of the points at which the density is evaluated and, in field y
, the estimated values of the density at these coordinates: density
产生一个列表,该列表在x
字段中包含评估密度的点的坐标,在y
字段中包含这些坐标处的密度的估计值:
> str(d)
List of 7
$ x : num [1:512] -0.348 -0.328 -0.307 -0.286 -0.266 ...
$ y : num [1:512] 0.00146 0.00256 0.00435 0.00717 0.01147 ...
......
To get a function from x
and y
, you can use the approxfun
function: 要从x
和y
获得一个函数,可以使用approxfun
函数:
> f <- approxfun(d$x, d$y)
> f(1)
[1] 0.3665273
> dexp(1, rate=1)
[1] 0.3678794
In your code you get d$y[1]
, which is the first value of d$y
. 在您的代码中,您将得到d$y[1]
,它是d$y
的第一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.