# [R] density estimates for fixed points

Karl Ove Hufthammer karl at huftis.org
Tue Feb 16 14:43:03 CET 2010

```On Tue, 16 Feb 2010 03:36:17 -0800 (PST) geir <geirdb at hotmail.com>
wrote:
> I want the density estimates for the points in a k x 2 matrix like for
> example
>
>                                   A=[(0,7,0.3),(0.1,0.2),...,(0.5,0.9)]^T
>
> which is not equally spaced, (and i do not need the density of every
> combination of these coordinates). So that the output is f(0.7,0.3),
> f(0.1,0.2), ... ,f(0.5,0.9), where "f" is the kernel estimator based on a
> and b.

*If* you required the density of every combination, it would be easiest
just to modify the definition of 'gx' and 'gy' in the 'kde2d' function.

But since you don't, why not calculate the density directly for each
point (e.g., in a loop). The formula is simple enough:

mean(dnorm(x-gx,sd=h1)*dnorm(y-gy,sd=h2))

where 'gx' and 'gy' is the point you want to estimate the density at,
and 'h1' and 'h2' are the bandwidths, typically 'h1=bandwidth.nrd(x)/4'
and 'h2=bandwidth.nrd(y)=4'.

Note that, depending on the number of coordinates you need to calculate
the kernel density esimate at, it may be faster to use the first
solution and just discard the estimates you don't need. (It will use a
lot more memory, though.)

--
Karl Ove Hufthammer

```