I don't have sucess for count the number of points by pixel in a raster when I don't have points. In my example:
#Create a raster and some points
xmn = 17;xmx = 23;ymn=42;ymx=49
my_ras<-raster(matrix(1:12,3,4), xmx=xmx, xmn=xmn,ymx=ymx,ymn=ymn)
my_points<-data.frame(x=runif(10,xmn,xmx), y=runif(10,ymn,ymx))
#Count the points
pointcount<- rasterize(my_points, my_ras, fun='count')
#Vizualize
plot(my_ras)
points(my_points, pch=16)
d <- data.frame(coordinates(pointcount), count=pointcount[])
summary(d)
# x y count
# Min. :17.75 Min. :43.17 Min. :1.000
# 1st Qu.:18.88 1st Qu.:43.17 1st Qu.:1.000
# Median :20.00 Median :45.50 Median :1.500
# Mean :20.00 Mean :45.50 Mean :1.667
# 3rd Qu.:21.12 3rd Qu.:47.83 3rd Qu.:2.000
# Max. :22.25 Max. :47.83 Max. :3.000
# NA's :6
Here, the problem is that I don't have the 0 values for pixels without points. I can't make a raster of zeros because in the real world in my rasters I have the NA
values outside a target area and make this was cause mistakes between real zeros (without points) and zeros outside the area boundary.
I need the zeros and NA values if have (obviously in this case not), any ideas? Maybe the sf
package has something like this.
Example data
library(raster)
xmn = 17;xmx = 23;ymn=42;ymx=49
ras <-raster(matrix(1:12,3,4), xmx=xmx, xmn=xmn,ymx=ymx,ymn=ymn)
points <-data.frame(x=runif(10,xmn,xmx), y=runif(10,ymn,ymx))
You can use background=0
instead of NA
pointcount<- rasterize(points, ras, fun='count', background=0)
If you now want to exclude some areas, you can use raster::mask
. Alternatively, if you have a raster with NA and zero values, you could use rasterize
with update=TRUE