【问题标题】:Clip raster to polygons in sf collection [R sf]将栅格裁剪为 sf 集合中的多边形 [R sf]
【发布时间】:2020-05-26 19:37:18
【问题描述】:

我想使用多边形的简单特征集合来剪辑栅格,这样我最终得到的栅格剪辑与我的 sf 集合中的多边形一样多。然后我想将每个光栅剪辑保存为 jpg。这是一个可重现的示例:

library(sf)
library(raster)
austria1 <- getData('GADM', country='AUT', level=1)
austria1 <- st_as_sf(austria1)
climate <- getData('worldclim', var='bio', res=2.5)

我想将气候剪辑到奥地利 1 的九个多边形,所以我最终得到了 9 个栅格剪辑。然后我想将这 9 个光栅剪辑保存为我的工作目录中的 jpg 文件。

感谢您的帮助!

标记

【问题讨论】:

    标签: r polygon raster sf clip


    【解决方案1】:

    示例数据

    library(sf)
    library(raster)
    austria <- getData('GADM', country='AUT', level=1)
    austria <- st_as_sf(austria)
    climate <- getData('worldclim', var='bio', res=2.5)
    climate <- climate[[1]]  # just the first layer
    

    一个for循环

    for (i in 1:nrow(austria)) {
        a <- austria1[i, ]
        fn <- tolower(paste0(a$NAME_1, ".jpg"))
        print(fn); flush.console()
        x <- crop(climate, a)
        y <- mask(x, a)
        jpeg(fn)       
        plot(y)
        dev.off()
    }
    

    您可能希望通过将一些默认参数更改为 jpeg 来改进 jpgs

    【讨论】:

    • 嗨罗伯特。这很好用,感谢您的帮助!对于更大的数据集(例如,数万个光栅剪辑),我想知道这是否可以在没有循环加速的情况下完成,例如使用 apply() 系列函数。你对此有什么想法吗?再次感谢。
    • 罗伯特,作为后续问题,mask() 命令在您的回答中做了什么?我检查了一些有无这条线的结果,但我不知道它在做什么。
    猜你喜欢
    • 2021-10-19
    • 2019-11-22
    • 2020-11-14
    • 2020-04-28
    • 2019-03-11
    • 2020-12-29
    • 2022-10-25
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多