The best approach is to coerce your spatstat "image" object to an sp object and use the over function or clip in the raster package. Here is a function to perform the coercion to an sp SpatialGridDataFrame.
as.SpatialGridDataFrame.im <- function(from){
offset=c(from$xrange[1] + 0.5 * from$xstep, from$yrange[1] + 0.5 * from$ystep)
cellsize = c(diff(from$xrange)/from$dim[2], diff(from$yrange)/from$dim[1])
dim = c(from$dim[2], from$dim[1])
gt = GridTopology(offset, cellsize, dim)
m = t(from$v[nrow(from$v):1, ])
data = data.frame(v = as.vector(m))
SpatialGridDataFrame(gt, data)
}
I'd convert the output to a raster object. Then:
require(spatstat)
require(sp)
require(raster)
set.seed(1985)
x <- runif(20)
y <- runif(20)
p <- SpatialPoints(coords = matrix(c(x, y), ncol = 2))
plot(p)
Then compute densities:
pp = ppp(x,y) # all points in a (0,1) default window
d <- density.ppp(pp, sigma = 0.1)
dp <- density.ppp(pp, sigma = 0.1, at="points")
That's Q2 answered! For Q1 I turn to the raster package:
dr = raster(d)
xyFromCell(dr, which.max(dr))
x y
[1,] 0.1523438 0.00390625
Note this is on slightly different data than you because I did it with data on a (0,1) square. Now I've got maptools
your max point comes out here:
> dr = raster(d)
> xyFromCell(dr, which.max(dr))
x y
[1,] 1.33514 0.3392474
Best Answer
The function get.knnx in package FNN can compute the N-nearest neighbours in point patterns.
now nn$nn.index is a matrix such that nn$nn.index[i,j] is the row in x1 of the two nearest neighbours to row i in x2 - sorted so that the nearest is [i,1], and the next neighbour is [i,2].
The function also returns the distances for you, and has some options to compute spatial indexes for very fast searches.