would really appreciate any help of rectifying my issue in R.
I have written a KDE function in R, and I am using MASS::kde2d as my reference, to plot and model crime data. The density values I am producing seem to be in the correct range, as well as the overall distribution of densities, but it appears to be flipped by 45 degrees through the plots origin.
Notice in the plot below that the shape is almost identical, but flipped.
Any help would be greatly appreciated! I have attached my 2d function below if anyone can spot an error. Thank you!
The input of the function is a spatial lattice, with coordinates at the center of the grid cells, crime locations in latitude then longitude order, bandwidth h and a switch parameter. I am looking at including other kernels hence the inclusion.
Kernel2D <- function(lattice, crime.locations, h, kernel){
if(is.data.frame(spatial.lattice)==FALSE) {lattice <- data.frame(lattice)}
d <- fields::rdist(lattice, crime.locations)
switch(kernel,
'normal'={
k=1
cat('k = 1, then rescaled so sum of densities = N. ')
cat("Normal - Function extends to boundary in all directions, applied to every location in the region regardless of h")
## This is the density calculation which iterates through the rows of d. I.e. for
## each cell in the lattice, it does a calculation on that row where the row contains the
## distances from that cell to each crime location. (Not trying to patronize anyone here
## with having dumb explanations! Trying to make it simple so I may understand it myself
## when explaining it to others haha) .
## I have assumed that this is correct as it it producing the same density shape as MASS::kde2d.
## There is an error when associating the density values to the right grid. Hmm. Ill have more of a think now.
density <- apply(d, 1, function(x) sum((1/(2*pi*h**2))*exp(-(x**2)/(2*h**2))))
k = nrow(crime.locations)/sum(density)
density <- k*density},
stop('Kernel Undefined. Available: triangular, uniform, negexp, normal, quartic'))
return(density)}