R 如何使用光栅和提取查找每个多边形内的平均值,但不包括某些值

R 如何使用光栅和提取查找每个多边形内的平均值,但不包括某些值,r,r-raster,R,R Raster,我有一个全球光栅文件,我想在其中计算每个国家的农药使用率。光栅文件包含值-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

我有一个全球光栅文件,我想在其中计算每个国家的农药使用率。光栅文件包含值-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的所有值,然后使用extract和mean将其与世界地图多边形相结合。代码如下:

# 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)
所以我得到的很多值都是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
你知道为什么吗

编辑:我已添加到光栅文件的链接:
显而易见的原因是这些国家的所有价值观都是NA。对于这些国家,你会得到

mean(NA, na.rm=TRUE)
#[1] NaN

因此,一切似乎都在按预期进行

看起来数据中也有NaN。检查数据是否为数字,并将NaN替换为NA。NaN在Matlab中使用。但是如果我不过滤它,它就不应该工作,不是吗?我现在检查了一下,原始光栅文件中似乎没有任何NaN。我还添加了一个指向光栅文件的链接。你还有其他想法吗?@SimonWoodward-R还有NaN。请尝试0/0或Inf-Inf链接返回404。@Edward我添加了另一个带有filedropper的链接,所以它不应该出现。
mean(NA, na.rm=TRUE)
#[1] NaN