Q: How to calculate observation per square km from spatial point data in R How to calculate the total no. of values i.e., no of values per square kilometer using point data with lat lon and each point with 1 observation as in sample data below ?
I want to know the total number of values per square km ( can be 1 or more).  I tried creating a raster but no luck.
den_dt <- structure(list(lat = c(49.0267, 49.0984, 49.1023, 49.107, 49.1077, 
49.1107, 49.1178, 49.1278, 49.1493, 49.1634, 49.2385, 49.2498, 
49.2834, 49.3235, 49.3467, 49.3796, 49.3878, 51.7285, 51.7319, 
51.7524, 51.7781, 51.7841, 51.7851, 51.7926, 51.8188, 51.9553, 
52.0331, 52.0342, 52.214, 52.2379, 52.4323, 52.492, 52.5312, 
52.5337, 52.5772, 52.6456, 52.656, 52.7196, 52.8439, 52.851), 
    lon = c(108.9861, 108.9342, 108.8654, 108.73, 109.0154, 108.9548, 
    108.8164, 108.6334, 108.9442, 108.6959, 119.4774, 119.5568, 
    117.5601, 117.5536, 119.3105, 119.9174, 117.594, 119.7592, 
    119.7747, 122.6436, 119.7638, 119.651, 122.6079, 119.7761, 
    119.7572, 121.9104, 121.8712, 122.4515, 121.7362, 121.7861, 
    121.9452, 121.9638, 121.471, 122.1595, 121.5216, 122.2008, 
    121.9462, 121.4331, 122.1229, 122.1054), val = c(1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), row.names = c(NA, -40L), class = c("tbl_df", 
"tbl", "data.frame"))


den_dt_ras <- rasterFromXYZ(den_dt)



A: You can do that like this

*

*create a raster r with the desired resolution and with an appropriate coordinate reference system (crs). If you want a spatial resolution of 1 km2 you need a planar crs.

*project your points p to the crs of the raster

*use rasterize(p, r, fun="count")
