1

在下面的例子中,extract 函数正确地告诉我们多边形 x2 内 r 的平均值是 5.14。但是,对于像 x1 这样小于栅格的多边形,提取返回值“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 的值在此处输入图像描述

4

1 回答 1

3

您可以使用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)

使用可从 获得的开发版本 (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
于 2021-06-29T17:28:50.227 回答