我正在尝试计算点要素与最近的 30 x 30 米栅格单元格边缘之间的距离(以米为单位)。我拥有的数据按季度汇总了五年(2016-2020),因此我需要在每年的每个季度迭代地进行此计算。单元格中的值无关紧要,我只需要每个点之间的矢量距离及其在给定季度和年份的最近栅格单元格。
样本数据
library(raster)
# set the extent of the study area
ext <- extent(401000, 402000, 4405000, 4406000)
# create a point file with drop locations
set.seed(123) # set a random seed for reproducibility
years <- c(2016, 2017, 2018, 2019, 2020)
quarters <- c("Q1", "Q2", "Q3", "Q4")
coords <- expand.grid(year = years, quarter = quarters,
x = runif(4, 401000, 402000),
y = runif(4, 4405000, 4406000))
points <- st_as_sf(coords, coords = c("x", "y"), crs = st_crs(3310))
points$year <- as.factor(points$year)
points$quarter <- as.factor(points$quarter)
# create a raster file with biomass estimates
raster <- raster(ext, res = 30)
values(raster) <- NA
non_empty_cells <- sum(runif(ncell(raster)) > 0.98)
if (non_empty_cells > 0) {
values(raster)[sample(which(is.na(values(raster))), non_empty_cells)] <- runif(non_empty_cells, 0, 10)
}
# plot the data
plot(raster, col = gray.colors(10, start = 0.8, end = 0))
plot(points, add = TRUE, col="red")
我假设您想要距离最近的具有值(不是 NA)的单元格的边界。如果您的栅格不是太大,您可以这样做:
示例数据
library(terra)
set.seed(123)
raster <- rast(ext=c(401000, 402000, 4405000, 4406000), res = 30, crs="local")
cells <- sample(ncell(raster), 20)
raster[cells] <- runif(length(cells))
years <- c(2016, 2017, 2018, 2019)
quarters <- c("Q1", "Q2", "Q3", "Q4")
points <- data.frame(year = years, quarter = quarters,
x = runif(4, 401000, 402000), y = runif(4, 4405000, 4406000))
pts <- vect(points, geom=c("x", "y"), crs=crs(raster))
解决方案
lns <- as.lines(as.polygons(raster, dissolve=FALSE))
#nearest(pts, lns) |> values()
# from_id from_x from_y to_id distance
#1 1 401127.5 4405665 7 136.23261
#2 2 401753.3 4405095 19 27.12752
#3 3 401895.0 4405384 10 74.71168
#4 4 401374.5 4405274 14 57.06026
如果距离相对于分辨率大,你也可以这样做
x <- distance(raster>0)
extract(x, pts)
# ID lyr.1
#1 1 169.70563
#2 2 42.42641
#3 3 108.16653
#4 4 84.85281
计算从单元格中心(点落入)到单元格中心(最近的单元格)的距离。