【问题标题】:Subset a raster using row/column index in terra使用 terra 中的行/列索引对栅格进行子集
【发布时间】:2021-12-26 03:37:15
【问题描述】:

我正在尝试在 terra 包中按行号和列号对栅格进行子集化。 显然这在栅格中很容易,至少没有地理范围和 crs: Subset a raster using 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 ]

【问题讨论】:

    标签: r gis raster terra


    【解决方案1】:

    您可以使用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))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 2012-08-06
      • 2016-01-14
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多