Search code examples
rkernel-densityprobability-density

Volume estimation with K_NN using R


I need to find the density of each point within a data set using k-NN density estimation algorithm. I understand the basic approach used for calculation as shown in the screenshot below. Complete slides at [link] enter image description here

I want to know is there any library within R which provides functions to calculate K-NN density estimation. Although there are some relevant questions on the same topic on stackoverflow, but none of them is properly answered.

Note: I found this question relevant, but again the answers do not work.


Solution

  • Although I did not find any R package which calculates density at a point. But, I followed these steps to calculate density at each point:

    1. I create a distance matrix for all the given points on plot (scatter-plot). Therefore for N points, I have N x N distance matrix, where each element (i, j) represents the Eucledian distance between ith and jth point.
    2. Now using distance matrix, For each point I sorted out (in increasing order) the distances with respect to other points. Therefore, now if I want the distance of kth neighbor, I simply choose the kth sorted distance.
    3. With Kth neighbor distance,I get the radius of circle. Therefore now I can substitute the radius value in the formula shown in the above picture. With this I am able to calculate density at a point.

    Note: In R, neighbors are sorted according to distance using order( ) function