在r中裁剪(子集)光栅图像(矩阵)

在r中裁剪(子集)光栅图像(矩阵),r,matrix,crop,subset,raster,R,Matrix,Crop,Subset,Raster,我希望能够将由矩阵组成的光栅图像分割成单独的矩阵/图像,以便比较它们 例如,假设我有这个光栅图像- library(grid) m = matrix(c( .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7

我希望能够将由矩阵组成的光栅图像分割成单独的矩阵/图像,以便比较它们

例如,假设我有这个光栅图像-

library(grid)      
m = matrix(c( .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7), nrow = 6, ncol=9)
grid.raster(m)
我想将其“裁剪”成6个单独的细胞,并将每个细胞保存为自己的基质。 我一直在想,基于尺寸,这可能是可能的

d <- dim(m)

d如果您一直知道您的子瓷砖是规则形状和方形的,那么还有其他方法/包来创建这些子瓷砖。但是,我认为
光栅
软件包是以一种非常通用、易于理解的方式完成您想要的任务的最佳解决方案:

m <- matrix(c( .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .7, .3, .7, .7, .3, .7, .7, .7, .7, .7, .7, .7), nrow = 6, ncol=9)


library(raster)

##  Construct a raster object from your matrix:
r <- raster(m)

##  Build index locations for upper left corners of grid:
i <- seq(1, ncol(r), ncol(r)/3)
j <- seq(1, nrow(r), nrow(r)/2)
indices <- expand.grid(i, j)

##  Crop to these grid locations, storing individual cropped
##    areas in a list object:
r_out <- lapply(1:nrow(indices), function(x){ 
  crop(r, 
    extent(r,
      indices[x,2], indices[x,2]+nrow(r)/2 - 1,
      indices[x,1], indices[x,1]+ncol(r)/3 - 1
    )
  )
})


##  Plot all individual rasters:
par(mfrow=c(2,3))
lapply(r_out, plot)
m
##  Re-mosaic raster objects:
args <- r_out
args['fun'] <- 'mean'
r_out_mos <- do.call(mosaic, args)
par(mfrow=c(1,1))
plot( r_out_mos )