栅格变化程度删除数据

问题描述 投票:0回答:1

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

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没有值,所以我实际上不能使用它来测试我在其他地方看到的错误。如何在不丢失所有数据的情况下扩展此栅格的范围?

r r-raster
1个回答
0
投票

如果我正确解释了这个问题,您要做的不是使用函数rast.smallextent change扩展expand()的范围,而是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()

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9ucU81Q0U1LnBuZyJ9” alt =“”>

# 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创建

© www.soinside.com 2019 - 2024. All rights reserved.