【问题标题】:How to find the mean within each polygon using raster and extract but excluding certain values如何使用栅格找到每个多边形内的平均值并提取但不包括某些值
【发布时间】:2020-07-16 01:02:49
【问题描述】:

我有一个全球栅格文件,我想在其中计算每个国家/地区的特定农药施用率。栅格文件包含值 -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

所以我的想法是简单地将光栅文件中所有

# 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

【问题讨论】:

  • 看起来数据中也有“NaN”。检查数据是否为数字,并将 NaN 替换为 NA。 NaN 用于例如Matlab。
  • 但是当我不过滤它时它应该不起作用,不是吗?我现在检查了一下,原始光栅文件中似乎没有任何 NaN。我还添加了光栅文件的链接。您还有其他想法吗?
  • @SimonWoodward - R 也有 NaN。试试0/0Inf - Inf
  • 链接返回404。
  • @Edward 我已经添加了另一个带有 filedropper 的链接,所以它不应该消失。

标签: r r-raster


【解决方案1】:

显而易见的原因是这些国家/地区的所有值都是NA。对于这些国家/地区,您将获得

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

所以一切似乎都按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2016-10-02
    • 1970-01-01
    • 2019-08-28
    • 2021-10-14
    相关资源
    最近更新 更多