网格单元内的采样点数 [英] Count of sampling points within a grid cell
问题描述
计算空间网格的每个网格单元内的采样点总数.
Calculate the total number of sampling points within each grid cell of a spatial grid.
我想制作一个网格并计算每个网格单元内采样点的总数.我创建了一个随机生成的数据和网格,并尝试使用 sf 和 raster 包计算网格单元格内的记录数,使用以前类似的 SO 问题,但没有成功.我还研究了提取功能.我对空间分析相当陌生.
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.
推荐答案
示例数据
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)
解决方案
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
或者,na.omit(cbind(1:ncell(r), values(r)))
这篇关于网格单元内的采样点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!