【问题标题】:terra::extract gives NaN when polygon is smaller than raster cell当多边形小于栅格单元时,terra::extract 给出 NaN
【发布时间】:2021-09-11 20:52:31
【问题描述】:

在下面的例子中,extract 函数正确地告诉我们多边形 x2 内 r 的平均值是 5.14。但是,对于像 x1 这样小于栅格的多边形,extract 返回值“NaN”

r <- rast(nrows = 10, ncol = 10, nlyrs = 1, vals = sample(1:10, 100, replace = TRUE), names = "temp")

x1 <- rbind(c(-145,-10), c(-145,-5), c(-140, -5), c(-140,-10))
x2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55))
z <- rbind(cbind(object=1, part=1, x1, hole=0),
           cbind(object=3, part=1, x2, hole=0))
colnames(z)[3:4] <- c('x', 'y')
p <- vect(z, "polygons")

plot(r)
plot(p, add = T)

test <- terra::extract(r, p, fun = mean, cell = TRUE)

test
  ID     temp
1  1      NaN
2  2 5.142857

如何在 x1 处获得 r 的值?

【问题讨论】:

    标签: r gis polygon raster terra


    【解决方案1】:

    您可以使用exact=TRUE

    示例数据

    library(terra)
    r <- rast(nrows = 10, ncols = 10, nlyrs = 1, vals =1:100, names = "temp")
    x1 <- rbind(c(-145,-10), c(-145,-5), c(-140, -5), c(-140,-10))
    x2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55))
    z <- rbind(cbind(object=1, part=1, x1), cbind(object=2, part=1, x2))
    colnames(z)[3:4] <- c('x', 'y')
    p <- vect(z, "polygons")
    

    默认

    extract(r, p, fun = mean)
    #  ID temp
    #1  1  NaN
    #2  2   53
    

    使用touches=TRUE,您可以获得所有被触摸的单元格

    extract(r, p, fun = mean, touches=TRUE)
    #  ID     temp
    #1  1 51.50000
    #2  2 52.62069
    

    或者你可以这样做

    e <- extract(r, p, exact=TRUE)
    head(e)
    #  ID temp    fraction
    #1  1   51 0.007539715
    #2  1   52 0.030169815
    #3  2   19 0.104219078
    #4  2   28 0.282198174
    #5  2   29 0.883159178
    #6  2   30 0.043386000
    
    x <- by(e[,2:3], e[,1], function(x) weighted.mean(x[,1], x[,2]))
    as.vector(x)
    # [1] 51.80006 52.21312
    

    (如果您熟悉该语法,请使用 dplyr 或 data.table)

    development 版本 (1.3.11),可从 install.packages('terra', repos='https://rspatial.r-universe.dev'),你得到:

    extract(r, p, fun=mean)
    #  ID temp
    #1  1 51.5
    #2  2 53.0
    

    你可以做到

    extract(r, p, fun=mean, exact=TRUE)
    #     ID     temp
    #[1,]  1 51.80006
    #[2,]  2 52.21312
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-30
      • 2015-09-27
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 2021-05-12
      相关资源
      最近更新 更多