R: How can I count how many points are in each cell of my grid?

穿精又带淫゛_ 提交于 2019-11-29 11:19:30

Here's one way to do it, first tabulating the frequency of cell numbers represented by points, then assigning these frequencies to the cells' values, and finally extracting the cells' coordinates and values.

library(raster)
r <- raster(xmn=0, ymn=0, xmx=10, ymx=10, res=1)
r[] <- 0
xy <- spsample(as(extent(r), 'SpatialPolygons'), 100, 'random')
tab <- table(cellFromXY(r, xy))
r[as.numeric(names(tab))] <- tab

Now we have something like this:

plot(r)
points(xy, pch=20)

We can extract the cells' coordinates with coordinates() and their values with values(r) or simply r[]:

d <- data.frame(coordinates(r), count=r[])

head(d)
##     x   y count
## 1 0.5 9.5     0
## 2 1.5 9.5     1
## 3 2.5 9.5     1
## 4 3.5 9.5     3
## 5 4.5 9.5     2
## 6 5.5 9.5     3    

The rasterize function can do that for you:

library(raster)
r <- raster(xmn=0, ymn=0, xmx=10, ymx=10, res=1)
xy <- spsample(as(extent(r), 'SpatialPolygons'), 100, 'random')

x <- rasterize(xy, r, fun='count')
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!