2

Calculate the total number of sampling points within each grid cell of a spatial grid.

I would like to make a grid and calculate the total count of sampling points within each grid cell. I created a randomly generated data and grid, and tried to calculate the number of records within a grid cells using both the sf and raster packages, using previous similar SO questions, but wthout success. I have also looked into the extract function. Im fairly new to spatial analysis.

 library(sf)
library(raster)
library(tidyverse)
library(mapview)
library(mapedit)

#Trial with sf package 
# load some spatial data. Administrative Boundary
#https://stackoverflow.com/questions/41787313/how-to-create-a-grid-of-       spatial-points
aut <- getData('GADM', country = 'aut', level = 0)
aut <- st_as_sf(aut)
#Try with polygons
grid <- aut %>% 
 st_make_grid(cellsize = 0.5, what = "polygons") %>% 
  st_intersection(aut)                               

#fake data
 lat<-runif(1000, 46.5, 48.5)
 lon<-runif(1000, 13,16)
pos<-data.frame(lat,lon)

 ggplot() + 
  geom_sf(data = aut) + 
  geom_sf(data = grid)+
geom_point(data=pos, aes(lon, lat)) 
#how to count number of records within each cell?  
 ########################################
#Trial with raster package
#https://stackoverflow.com/questions/32889531/r-how-can-i-count-how-   many-points-are-in-each-cell-of-my-grid
 r<-raster(xmn=13, ymn=46.5, xmx=16, ymx=48.5, res=0.5)
r[] <- 0
#How do I use the pos data here
xy <- spsample(as(extent(r), 'SpatialPolygons'), 100, 'random')
tab <- table(cellFromXY(r, xy))
r[as.numeric(names(tab))] <- tab
plot(r)
points(xy, pch=20)
d <- data.frame(coordinates(r), count=r[])

I would like to obtain a table with number of sampling points.

  • Have you looked into stat_bin_2d? alternatively stat_hex_bin? these calculate the count and density per bin. – Kresten May 20 '19 at 09:41
  • Thanks for your advice. I had not considered stat_bin_2d or stat_hex_bin. How do you get the count of the bins? I just started to play with these funcitons but so far not got anything meaningful out of it yet. ggplot(pos, aes(lon, lat)) + geom_bin2d(binwidth = 2) + stat_bin2d(geom = "text", aes(label = ..count..),binwidth = 10) + scale_fill_gradient(low = "white", high = "red") – Stefán Áki Ragnarsson May 20 '19 at 10:41

3 Answers3

4

counting the lengths of st_intersects (note: not st_intersection) would give you a vector of points contained in each grid cell:

library(sf)
library(raster)
library(tidyverse)
library(mapview)
library(mapedit)

#Trial with sf package 
# load some spatial data. Administrative Boundary
#https://stackoverflow.com/questions/41787313/how-to-create-a-grid-of-       spatial-points
aut <- getData('GADM', country = 'aut', level = 0)
aut <- st_as_sf(aut)
#Try with polygons
grid <- aut %>% 
  st_make_grid(cellsize = 0.5, what = "polygons") %>% 
  st_intersection(aut)                               

#fake data
lat<-runif(1000, 46.5, 48.5)
lon<-runif(1000, 13,16)
pos<-data.frame(lat,lon)

pos = st_as_sf(pos, coords = c("lon", "lat"), crs = 4326)

tab = st_intersects(grid, pos)
lengths(tab)
[1]  0  0  0  0  4 24 23 34 23 13 14  0  0  0  0  0  0  0  3 38 40 48 46 47 33  0  0  0  0  0  0  0
[33]  0 35 48 51 35 38 44  0  0  0  0 44 43 41 53 44 32  0  0  0  0  8  8 10 12  7  0  0  0  0  0

If you then want to bind that to grid as a sf object you could do:

grid = st_sf(n = lengths(tab), geometry = st_cast(grid, "MULTIPOLYGON"))

mapview(grid, zcol = "n")
TimSalabim
  • 5,604
  • 1
  • 25
  • 36
2

Example data

library(raster)   
aut <- getData('GADM', country = 'aut', level = 0)
r <- raster(aut, res=0.5)
lat <- runif(1000, 46.5, 48.5)
lon <- runif(1000, 13,16)
# note that you should use (lon, lat), in that order!
pos <- data.frame(lon, lat)

Solution

r <- rasterize(pos, r, fun="count")
plot(r)

To get a table, you can do

x <- rasterToPoints(r)
z <- cbind(cell=cellFromXY(r, x[,1:2]), value=x[,3])
head(z)
#     cell value
#[1,]   22    4
#[2,]   23   45
#[3,]   24   36
#[4,]   25   52
#[5,]   26   35
#[6,]   27   38

Or, alternatively, na.omit(cbind(1:ncell(r), values(r)))

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
1

Try

ggplot(pos, aes(x = lon, y=lat)) + 
geom_bin2d(binwidth = 2) +
stat_bin_2d(aes(label=stat(count)), binwidth=2, geom="text", position="identity") +
scale_fill_gradient(low = "white", high = "red")

enter image description here

Kresten
  • 1,758
  • 12
  • 18
  • Thanks. Could your provide an advice of how to overlay this figure over a map e.g. the map of Austria I provide as an example of. It a sf object, but it is possible to visialise sf objects with geom_sf. I have been trying without success. – Stefán Áki Ragnarsson May 20 '19 at 12:16
  • I am not familiar with sf objects but whenever I need to plot some spartial data I got to leaflet (https://rstudio.github.io/leaflet/shapes.html) – Kresten May 20 '19 at 12:20