我正在比较 terra::extract 和exactextractr ::exact_extract 的功能。我注意到对于 terra::extract,
exact = TRUE
有时不起作用,但 weight=TRUE
可以。
exact
与weight
比较好?extract
中的参数exact=TRUE
是否存在错误?exact_extract(rast, poly)
中那样从多边形中获取像素重叠的比例,但是对于terra::extract
?library(sf)
library(terra)
library(exactextractr)
rt=list(test1= matrix(1:100, ncol=10),
test2= matrix(201:300, ncol=10))
rast1 <- terra::rast((rt$test1))
rast2 <- terra::rast((rt$test1+2))
rast = c(rast1, rast2)
val1 = 0
val2 = 1.50
vac1= c(val1, val1, val2, val1, val2, val2, val1, val2, val1, val1)
vm1 = matrix(vac1, ncol = 2, byrow = TRUE)
pol1 = st_polygon(list(vm1))
pol2 = st_polygon(list(vm1+2))
pol3= st_polygon(list(vm1+4, vm1+6))
poly = st_sfc(pol1, pol2, pol3) %>% st_as_sf()
names(rast) <- c('t1', 't2')
rast_m=mask(rast, poly)
pt.pix = xyFromCell(rast, 1:100)
plot(rast_m[[1]]);plot(poly, add = TRUE)
plot(st_multipoint(pt.pix), add= TRUE, pch = ".", cex = 5)
text(st_multipoint(pt.pix+.15), labels = values(rast[[1]]))
values(rast_m[[1]]) %>% mean(., na.rm = T)
terra::extract(x = rast, y = poly, 'sum', exact = FALSE)
terra::extract(x = rast, y = poly, 'sum', exact = TRUE)
给出
Error: TopologyException: Input geom 1 is invalid: Hole lies outside shell at 6 6
但是有了
weight
,它就有效了...
terra::extract(x = rast, y = poly, 'mean', weight = TRUE)
# (10+10+4.5+19/4)/(1.5^2)
exact_extract(rast, poly, 'mean')
e = exact_extract(rast, poly)
那是因为
poly
几何图形无效:
sf::st_is_valid(poly)
# [1] TRUE TRUE FALSE
poly <- sf::st_make_valid(poly)
terra::extract(x = rast, y = poly, 'sum', exact = TRUE)
# ID t1 t2
# 1 1 29.25 33.75
# 2 2 69.75 74.25
# 3 3 261.00 270.00