1

我正在尝试在包 terra 中按行号和列号对栅格进行子集化。显然,这在栅格中很容易,至少没有地理范围和 crs: 使用 row/column index 对栅格进行子集。但我无法让它在 terra 中工作。必须有一个简单的方法。terra::subset 只选择栅格的图层。

期待有人问为什么:在对高程栅格进行采样并计算斜率和坡向之前,我用行和列填充了栅格,这依赖于相邻的单元格。现在我需要去掉那些填充的行和列。

library(terra)
EXT <- c( -108, -105, 39, 42 )
R <- rast( extent=EXT, ncol=14, nrow=14, crs="epsg:4326" )
R[] <- 1:ncell(R)

# Now try to strip off the outer 2 rows and columns
crop( x=R, y=ext( 3, 12, 3, 12 ) )
# Error: [crop] extents do not overlap

# Normal R-style subsetting also does not work,
# just gives values of that subset
R[ 3:12, 3:12 ]
4

1 回答 1

4

您可以使用子集drop=FALSE

library(terra)
r <- rast( extent=c( -108, -105, 39, 42 ), ncol=14, nrow=14, crs="epsg:4326" )
values(r) <- 1:ncell(r)

x <- r[ 4:12, 3:10, drop=FALSE]
x
#class       : SpatRaster 
#dimensions  : 9, 8, 1  (nrow, ncol, nlyr)
#resolution  : 0.2142857, 0.2142857  (x, y)
#extent      : -107.5714, -105.8571, 39.42857, 41.35714  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 (EPSG:4326) 
#source      : memory 
#name        : lyr.1 
#min value   :    45 
#max value   :   164 

核实

xy <- xyFromCell(x, cells(x))
range(rowFromY(r, xy[,2]))
#[1]  4 12
range(colFromX(r, xy[,1]))
#[1]  3 10

至于“为什么”,我会用它crop(slope, original)来删除填充值。也就是说,的第二个参数crop应该是您的原始 SpatRaster 没有填充单元格,或其 SpatExtent ( ext(orginal))

于 2021-11-14T18:34:24.690 回答