[英]R terra calculate area moment of inertia OR how to get (weighted) raster-cell distance from patch-centroid
I'm trying to calculate a measure akin to the moment of inertia using a raster layer and I am struggling to figure out how to get the distance of each cell to a patch's centroid and then extracting both that distance and the cell's value.我正在尝试使用栅格层计算类似于惯性矩的度量,并且我正在努力弄清楚如何获取每个单元格到补丁质心的距离,然后提取该距离和单元格的值。
I want to calculate the moment of inertia (get the squared distance of each cell to its patches centroid, multiply by value of cell, sum these values by patch, and then divide by the sum of all values per patch).我想计算惯性矩(获取每个单元格到其补丁质心的平方距离,乘以单元格的值,将这些值按补丁进行求和,然后除以每个补丁的所有值的总和)。 I provide a simplified set-up below.
我在下面提供了一个简化的设置。 The code creates a simple raster layer, patches clusters of cells, and gets their centroids.
该代码创建了一个简单的栅格图层、修补单元簇并获取它们的质心。 I know that the function in question to use next is probably terra::distance (maybe in combination with terra::zonal?!) -- how do I calculate the distance by patch ?
我知道接下来要使用的函数可能是 terra::distance (可能与 terra::zonal 结合使用?!)-如何通过 patch计算距离?
#lonlat
library(terra)
r <- rast(ncols=36, nrows=18, crs="+proj=longlat +datum=WGS84")
r[498:500] <- 1
r[3:6] <- 1
r[111:116] <- 8
r[388:342] <- 1
r[345:349] <- 3
r_patched <- patches(r, directions = 8, allowGaps = F)
testvector <- terra::as.polygons(r_patched, trunc=T, dissolve = T)
p_centr <- geom(centroids(testvector), df=T)
##next steps
#1. get distance of each cell from patch's centroid
#r <- distance(r)
#2. multiply cell value by squared distance to centroid
I think you need to loop over the patches.我认为您需要遍历补丁。 Something like this:
像这样的东西:
p_centr <- centroids(testvector)
v <- rep(NA, length(p_centr))
for (i in 1:length(p_centr)) {
x <- ifel(r_patched == p_centr$patches[i], i, NA)
x <- trim(x)
d <- distance(x, p_centr[i,])
d <- mask(d, x)
# square distance and multiply with cell values
d <- d^2 * crop(r, d)
v[i] <- global(d, "sum", na.rm=TRUE)[[1]]
}
v / sum(v)
#[1] 1.213209e-05 1.324495e-02 9.864759e-01 2.669833e-04
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.