我想使用bbox或已知范围(即行和列中的10个像素)裁剪光栅.

下面你可以看到一个可复制的例子:

library(terra)
r <- terra::set.ext(rast(volcano), terra::ext(0, nrow(volcano), 0, ncol(volcano)))
plot(r)

xmin <- xmin(r)
ymax <- ymax(r)
rs <- res(r)

n <- 10 # i.e. of rows and cols size
xmax <- xmin + n * rs[1] 
ymin <- ymax - n * rs[2]

x <- crop(r, c(xmin, xmax, ymin, ymax))
plot(x)

plot x

预期的循环是:

  • 完成所有光栅(r)长度裁剪,并将每个光栅片段临时保存到数据中.框架(或data.table、光栅、光栅、列表)

推荐答案

对于你为什么要这样做,有更多的背景知识是很有用的.从你的问题中也不清楚你是否希望裁剪区域重叠;我猜你不想那样.

你可以这样说:

library(terra)
r <- rast(volcano)
n <- 10

获取感兴趣的起始细胞

rows <- seq(1, nrow(r), by=n)
cols <- seq(1, ncol(r), by=n)    
cells <- cellFromRowColCombine(r, rows, cols)

获取坐标

# upper-left coordinates of the starting cells 
xy <- xyFromCell(r, cells)
rs <- res(r)
xy[,1] <- xy[,1] - rs[1]/2
xy[,2] <- xy[,2] + rs[2]/2

# add the lower-right coordinates of the end cell
xy <- cbind(xy[,1], xy[,1] + n*rs[1], xy[,2] - n*rs[2], xy[,2])

和循环

x <- lapply(1:nrow(xy), function(i) {
         crop(r, xy[i,])
       })
    

验证

e <- lapply(x, \(i) ext(i) |> as.polygons()) |> vect()
plot(r)
lines(e, col="blue", lwd=2)

enter image description here

sapply(x, dim) |> t() |> head()
#     [,1] [,2] [,3]
#[1,]   10   10    1
#[2,]   10   10    1
#[3,]   10   10    1
#[4,]   10   10    1
#[5,]   10   10    1
#[6,]   10   10    1

或者使用基于起始单元和结束单元编号的另一种方法(为了实现这一点,您需要terra 1.5-25,目前您可以使用install.packages('terra', repos='https://rspatial.r-universe.dev')安装的开发版本)

srows <- seq(1, nrow(r), by=n)
scols <- seq(1, ncol(r), by=n)
erows <- pmin(nrow(r), srows+n-1)
ecols <- pmin(ncol(r), scols+n-1)
scell <- cellFromRowColCombine(r, srows, scols)
ecell <- cellFromRowColCombine(r, erows, ecols)
cells <- cbind(scell, ecell)

x <- lapply(1:nrow(cells), function(i) {
        e <- ext(r, cells[i,])
        crop(r, e)
    })
    

R相关问答推荐

通过R访问MoveApps API

R通过字符串中的索引连接数据帧r

即使声明引发错误,R函数也会在第二次try 时返回结果

无法在我的情节中表现出显着的差异

selectInput不返回ALL,并将因子转换为shiny 的数字

基于多列将值链接到NA

在数组索引上复制矩阵时出错

R函数,用于生成伪随机二进制序列,其中同一数字在一行中不出现超过两次

如何使用ggplot对堆叠条形图进行嵌套排序?

在使用tidyModels和XGBoost的二进制分类机器学习任务中,所有模型都失败

如何对r中包含特定(未知)文本的行求和?

为什么这个表格格罗布不打印?

是否可以将线性模型的p值添加到tbl_summary中

为R中的16组参数生成10000个样本的有效方法是什么?

为什么将负值向量提升到分数次方会得到NaN

R-找出存在其他变量的各种大小的所有组合

在同一单元格中创建包含整数和百分比的交叉表

抽样变换-REXP与RWEIBUR

如果极点中存在部分匹配,则替换整个字符串

把代码写成dplyr中的group_by/摘要更简洁吗?