英文:
How to get a SpatRaster of indices of the nearest NA cell in R terra?
问题
从数字高程模型中,我尝试生成水流和其周围地形高度差的栅格。如果水流是平坦的,这将很容易。
给定一个栅格,其中包含水流的单元格为NA,terra::distance() 函数可以输出从每个单元格到最近的NA单元格的距离的栅格。
是否有类似的函数可以输出最近NA单元格的索引的栅格?
或者对于我的用例来说更好的是,可以输入两个完全重叠的栅格,一个是带有水流位置NA值的蒙版,另一个是DEM,然后输出最近NA单元格的高度的栅格?
我花了一些时间在terra文档中寻找这样的函数但没有成功。你能想到在不修改terra的情况下实现相同目标的方法吗?
如果没有简单的方法,我会尝试用点对我的水流进行采样,创建泰森多边形图,为每个泰森多边形分配其对应点的高度,并将其栅格化。
英文:
From a digital elevation model, I'm trying to generate a raster of the difference in elevation between a water stream and its surroundings. That would be easy if the water stream was flat, but it is not.
Given a raster where the cells containing the stream are NA, the terra::distance() function can output a raster of the distance from each cell to the nearest NA cell.
Is there some similar function which could output a raster of the index of the nearest NA cell instead ?
Or even better for my use case, that would take in input two exactly overlapping rasters, one being the mask with NA values where the stream lies, and the other the DEM, and output a raster of either the elevation of the nearest NA cell ?
I have spent some time looking for such a function in the terra documentation without success. Can you think of a way to achieve the same thing without modifying terra ?
If there is no easy way to do it, I'll try sampling my stream with points, create a Voronoi diagram, assign each Voronoi polygon the elevation of its corresponding point, and rasterize that.
答案1
得分: 0
问题没有明确定义,因为可能存在多个最近的单元格,但以下是两种可能的方法。
示例数据
library(terra)
elv <- rast(system.file("ex/elev.tif", package="terra"))
riv <- vect(system.file("ex/lux.shp", package="terra"))[12] |> as.lines()
riv$val <- NA
elv <- rasterize(riv, elv, "val", update=TRUE)
您可以计算NA单元格的焦点均值
felv <- focal(elv, 3, mean, na.policy="only")
或者,您可以找到相邻单元格的值
e <- extract(elv, riv, cell=TRUE)
a <- adjacent(elv, e$cell)
a <- cbind(a, extract(elv, a[,2])) |> na.omit()
b <- aggregate(a[, "elevation", drop=F], a[, "from", drop=FALSE], mean)
这些是您可能要遵循的两种方法。
英文:
The problem is not well defined as there can be multiple nearest cells, but here are two approaches that you might follow.
Example data
library(terra)
elv <- rast(system.file("ex/elev.tif", package="terra"))
riv <- vect(system.file("ex/lux.shp", package="terra"))[12] |> as.lines()
riv$val <- NA
elv <- rasterize(riv, elv, "val", update=TRUE)
You can compute the focal mean for the NA cells
felv <- focal(elv, 3, mean, na.policy="only")
Alternatively, you can find the values for adjacent cells
e <- extract(elv, riv, cell=TRUE)
a <- adjacent(elv, e$cell)
a <- cbind(a, extract(elv, a[,2])) |> na.omit()
b <- aggregate(a[, "elevation", drop=F], a[,"from", drop=FALSE], mean)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论