r 栅格更改范围删除数据

r raster changing extent removes data

我想弄清楚为什么在更改范围后我会收到一些简单栅格代数的错误消息。为了证明这一点,我想我会在另一个堆栈溢出问题上的一些代码之后创建一个玩具示例。

library(raster)    
## Create a matrix with random data
xy <- matrix(rnorm(400),20,20)

# generate two extents to apply
globeExtent <- extent(c(-180, 180, -90, 90))
smallerExtent <- extent(c(-180, 180, -59.5, 83.5))

# Turn the matrix into a raster
rast.smallextent <- raster(xy)
extent(rast.smallextent) <- smallerExtent

rast.globeExtent <- setExtent(rast.smallextent, ext = globeExtent, keepres = TRUE)
mathtest <- rast.globeExtent - rast.smallextent

mathtest 代码行失败,因为 rast.globeExtent 没有值,所以我实际上不能用它来测试我在别处看到的错误。如何在不丢失所有数据的情况下扩展此栅格的范围?

如果我对问题的理解正确,你需要做的不是改变rast.smallextent的范围,而是扩展 栅格,使用函数 expand()。像这样:

library(raster) 
#> Loading required package: sp
library(tmap)
## Create a matrix with random data
xy <- matrix(rnorm(400),20,20)

# generate two extents to apply
globeExtent   <- extent(c(-180, 180, -90, 90))
smallerExtent <- extent(c(-180, 180, -20, 20))

# Turn the matrix into a raster
rast.smallextent <- raster(xy)
extent(rast.smallextent) <- smallerExtent
tmap::tm_shape(rast.smallextent) + tmap::tm_raster() + tmap::tm_grid()

# extend the raster over a wider area, while keeping the values
# 
rast.globeExtent  <- extend(rast.smallextent, globeExtent)

# Now rast.globeExtent is "expanded", but values are still there:

rast.globeExtent
#> class      : RasterLayer 
#> dimensions : 90, 20, 1800  (nrow, ncol, ncell)
#> resolution : 18, 2  (x, y)
#> extent     : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#> crs        : NA 
#> source     : memory
#> names      : layer 
#> values     : -3.606916, 2.795636  (min, max)
tmap::tm_shape(rast.globeExtent) + tmap::tm_raster() + tmap::tm_grid()

# Math now works on the intersection, although results are "cropped" on 
# the intersecting area

rast.globeExtent <- rast.globeExtent + 1 #add 1 to check math is correct
mathtest <- rast.globeExtent - rast.smallextent
#> Warning in rast.globeExtent - rast.smallextent: Raster objects have different
#> extents. Result for their intersection is returned
mathtest
#> class      : RasterLayer 
#> dimensions : 20, 20, 400  (nrow, ncol, ncell)
#> resolution : 18, 2  (x, y)
#> extent     : -180, 180, -20, 20  (xmin, xmax, ymin, ymax)
#> crs        : NA 
#> source     : memory
#> names      : layer 
#> values     : 1, 1  (min, max)
tmap::tm_shape(mathtest) + tmap::tm_raster() + tmap::tm_grid()

HTH!

reprex package (v0.3.0)

于 2019-12-13 创建