【问题标题】:Calculating the distance from points and the closest raster cell of a certain value in R计算点与R中某个值的最近栅格单元的距离
【发布时间】:2021-05-03 22:15:45
【问题描述】:

我正在尝试计算从空间点到特定值/类型的栅格单元的距离。在我的数据中,每个点代表一棵树,我想知道该点与不同类别的栅格单元(草、森林、不透水表面等)的距离。我尝试了 distanceFromPoints ,但它返回了一个距离栅格,我感兴趣的是一个数据框,其中包含从每个点到每种土地覆盖类型的最近栅格单元的距离。

#example raster
library(raster)
r <- raster(nrow=100, ncol=100)
r[] <- round(runif(ncell(r),1,4),0)
plot(r)

#example points
x <- c(-110, -50, 25, 150)
y <- c(50, -25, 70, 2)
df <- data.frame(cbind(x,y))
df$n <- c("pt1","pt2","pt3","pt4")

library(sp)
sp <- SpatialPoints(c, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs"))
plot(sp, add=TRUE)

我想要的输出是这样的:

    x   y   n   dist.cat1 dist.cat2 dist.cat3 dist.cat4
1 -110  50 pt1        12         3         5         9
2  -50 -25 pt2         1         2         1        27
3   25  70 pt3         4        14        29         5
4  150   2 pt4        23         2        15         2

其中 dist.cat1 表示从点 (n) 到最近的具有类别 1 值的栅格像元的距离。

【问题讨论】:

    标签: r distance raster


    【解决方案1】:

    它不漂亮,但你可以做这样的事情。

    library(terra)
    # simulate raster
    r <- raster(nrow=100, ncol=100)
    r[] <- round(runif(ncell(r),1,4),0)
    # simulate coordinates
    x <- c(-110, -50, 25, 150)
    y <- c(50, -25, 70, 2)
    
    xy <- cbind(x, y)
    out <- list()
    for (i in 1:nrow(xy)) {
        d <- distanceFromPoints(r, xy[i,,drop=F])
        out[[i]] <- zonal(d, r, min)[,2]
    }
    a <- do.call(rbind, out)
    
    b <- cbind(x, y, id=1:4, a)
    colnames(b)[4:7] <- paste0("dcat", 1:4)
    #        x   y id     dcat1    dcat2     dcat3    dcat4
    #[1,] -110  50  1 145303.98 252442.9 331242.16 102200.3
    #[2,]  -50 -25  2  57449.51 186127.4 136371.57 138753.8
    #[3,]   25  70  3 280556.71 235822.1 110116.94 342537.4
    #[4,]  150   2  4 279410.53 161549.5  99779.32 473517.4
    

    这些是从点到类的最近单元中心的距离(以 m 为单位)。因此,除非一个点位于单元格的中心,否则没有零。如果你愿意,你可以解决这个问题。

    你也可以像这样从细胞中心开始

    xy <- cbind(x, y)
    out <- list()
    for (i in 1:nrow(xy)) {
        d <- rasterize(xy[i,,drop=F], r)
        d <- distance(d)
        out[[i]] <- zonal(d, r, min)[,2]
    }
    a <- do.call(rbind, out)
    a 
    #         [,1]     [,2]     [,3]     [,4]
    #[1,] 200226.1 413979.1 249315.6      0.0
    #[2,]      0.0 199349.5 200816.0 199035.8
    #[3,] 324904.0 365442.0 142051.4 400308.1
    #[4,] 260746.8      0.0      0.0 398093.3
    

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 2013-11-02
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 2018-12-02
      • 2021-07-27
      • 2021-10-16
      相关资源
      最近更新 更多