我想从包含农药使用情况的光栅文件中提取一些施用率、总施用量和面积。我有很多文件需要执行此操作,而光栅速度很慢,因此我需要在 terra 中执行此操作,但很难复制 mask 功能。
这是栅格中的代码(从此处复制:Using raster to calculate the mean application and total application of pesticides, but numbers not adding up):
library(tidyverse)
## With raster ----
data(wrld_simpl)
r <- raster::raster("https://raw.github.com/hansronald/Pesticide-data/master/APR_Soybean_Glyphosate_2015_L.tif")
r <- raster::clamp(r, lower=0, useValues=FALSE)
# area in ha
a <- raster::area(r) * 100
## Get the mean application rate
mean_app <- raster::extract(r, wrld_simpl, fun = mean, na.rm = TRUE)
rtot <- r * a
## Get the total application for each country
tot_app <- raster::extract(rtot, wrld_simpl, fun = sum, na.rm = TRUE)
## Get the total area for each country
rarea <- mask(a, r)
tot_area <- raster::extract(rarea, wrld_simpl, fun = sum, na.rm = TRUE)
在陆地上
## Terra ----
data(wrld_simpl)
wrld_simpl = vect(wrld_simpl)
r <- terra::rast("https://raw.github.com/hansronald/Pesticide-data/master/APR_Soybean_Glyphosate_2015_L.tif")
r <- terra::clamp(r, lower=0, values=FALSE)
# area in ha
a <- terra::area(r) * 100
mean_app <- terra::extract(r, wrld_simpl, fun = mean, na.rm = TRUE)
rtot <- r * a
tot_app <- terra::extract(rtot, wrld_simpl, fun = sum, na.rm = TRUE)
rarea <- terra::mask(a, r)
tot_area <- terra::extract(rarea, wrld_simpl, fun = sum, na.rm = TRUE)
但是当我尝试使用掩码时出现此错误:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘mask’ for signature ‘"numeric", "SpatRaster"’
有什么想法可以解决这个问题吗?
最佳答案
terra
中的 area
方法与 raster
中的方法略有不同。在 terra 中,它可以返回 SpatRaster(每个像元的面积)或数字(总面积)。在您的情况下,a
是总面积,因此您不能将其与mask
一起使用也就不足为奇了(当然,在每一步检查对象是很好的。 )
您可以使用sum=FALSE
得到您想要的。通过添加 mask=TRUE
您可以完全跳过掩码步骤。
a <- terra::area(r, sum=FALSE, mask=TRUE) / 10000
另请注意,单位为 m2。
关于r - 如何使用 terra 复制此光栅脚本(特别是与掩模功能作斗争)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67449001/