我有一个全局栅格文件,我想在其中计算每个国家/地区内农药的特定施用率。栅格文件包含值-2(代表水),-1.5(代表缺失值)和-1(代表农药禁用),这些值没有意义,我需要排除这些值并计算所有其他值。
# My raster file is called rast and has these properties
> rast
class : RasterLayer
dimensions : 1681, 4306, 7238386 (nrow, ncol, ncell)
resolution : 0.08333333, 0.08333333 (x, y)
extent : -178.9167, 179.9167, -56.0425, 84.04084 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
names : APR_Corn_2.4.d_2015_L
因此,我的想法是用NA替换光栅文件中所有<0的值,然后使用提取和均值将其与世界地图多边形组合。这是代码:
# Load packages and polygon data
library(raster)
library(maptools)
data(wrld_simpl)
# Replace all the negative values with NA
rast.new = rast
rast.new[rast.new < 0] = NA
# Get the mean applcation rate (kg/ha) for each country
national_mean_apr_extr = raster::extract(rast.new, wrld_simpl, fun = mean, na.rm = TRUE)
这就是我得到的
> national_mean_apr_extr
[,1]
[1,] NaN
[2,] 4.422384e-02
[3,] 8.333350e-03
[4,] 3.638522e-02
[5,] 1.683824e-02
[6,] 3.001397e-04
[7,] NaN
[8,] 2.022979e-01
[9,] 4.490954e-02
[10,] NaN
[11,] NaN
[12,] NaN
[13,] NaN
[14,] 1.050294e-02
[15,] 6.948954e-02
所以我得到的很多值都是NaN,但我不知道为什么。
如果我不执行用NA替换所有负数的步骤,那似乎可行,并且我也没有得到任何NaN,但是数字当然是不正确的:
# Get the mean applcation rate (kg/ha) for each country
national_mean_apr_extr = raster::extract(rast, wrld_simpl, fun = mean, na.rm = TRUE)
> national_mean_apr_extr
[,1]
[1,] -1.500000000
[2,] -1.500888377
[3,] -0.494337678
[4,] -0.038511559
[5,] -1.340424282
[6,] -0.831025496
[7,] -2.000000000
[8,] -0.946029966
[9,] -1.483374534
[10,] -1.500000000
[11,] -1.875000000
[12,] -2.000000000
[13,] -1.828125000
[14,] -1.490271067
[15,] -0.754035134
任何想法为什么会这样?
编辑:我已经添加了指向栅格文件的链接:http://www.filedropper.com/aprcorn24-d2015l
显而易见的原因是这些国家的所有价值均为NA
。对于这些国家,您将获得
mean(NA, na.rm=TRUE)
#[1] NaN
因此,所有人似乎都按预期工作。