rentropykernel-densityestimation

finding probability of area in kernel density estimation using kde2d


I'm having a very hard time to calculate the probability of a point being in a particular area in a kernel density estimation. This will be used to show the probabilty of an animal moving around in a specific area.

Here is my sample data:

set.seed(123)
x <- runif(100,0,100)
y <- runif(100,0,100)

n <- 11
lims <- c(range(0,100), range(0,100))

f1 <- MASS::kde2d(x = x,y = y ,n = n, lims = lims)

Where f1$z holds the density estimations in a matrix. The corresponding plot is shown below:

library('plot.matrix')
plot(f1$z)

density estimates

Now, my goal is to find for example the probability of a point being in the cell surrounded in blue.

I wonder, if this can be achieved be simply calculating:

library(raster)
raster <- raster(f1)
df <- as.data.frame(raster,xy=T)
df$layer / sum(df$layer)

But I assume the solution must be to integrate somehow like described in here.

Thank you!


Solution

  • The point surrounded in blue is the point f1$z[3, 2]. Multiply this value by the cell size as computed in the code you link to and have

    xlim <- range(f1$x)
    ylim <- range(f1$y)
    cell_size <- (diff(xlim) / n) * (diff(ylim) / n)
    
    f1$z[3, 2] * cell_size
    #[1] 0.003765805
    

    Off-topic

    To see that this will compute the probability over that cell, compute the density over all cells f1$z. It must be equal to 1.

    norm <- sum(f1$z) * cell_size  # normalizing constant
    sum(f1$z)*cell_size/norm
    #[1] 1