簡體   English   中英

R terra 計算區域慣性矩或如何從補丁質心獲取(加權)柵格單元距離

[英]R terra calculate area moment of inertia OR how to get (weighted) raster-cell distance from patch-centroid

我正在嘗試使用柵格層計算類似於慣性矩的度量,並且我正在努力弄清楚如何獲取每個單元格到補丁質心的距離,然后提取該距離和單元格的值。

我想計算慣性矩(獲取每個單元格到其補丁質心的平方距離,乘以單元格的值,將這些值按補丁進行求和,然后除以每個補丁的所有值的總和)。 我在下面提供了一個簡化的設置。 該代碼創建了一個簡單的柵格圖層、修補單元簇並獲取它們的質心。 我知道接下來要使用的函數可能是 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


我認為您需要遍歷補丁。 像這樣的東西:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM