【问题标题】:How to write raster bylayer using terra package in R?如何在 R 中使用 terra 包编写光栅分层?
【发布时间】:2021-09-16 01:54:54
【问题描述】:

我想使用terra 包逐层编写栅格。我正在使用以下代码

library(terra)

# first create a raster
r1 <- r2 <- r3 <- rast(nrow=10, ncol=10)
# Assign random cell values
values(r1) <- runif(ncell(r1))
values(r2) <- runif(ncell(r2))
values(r3) <- runif(ncell(r3))
s <- c(r1, r2, r3)
s
plot(s)

writeRaster(s, names(s), overwrite=TRUE)

它给了我以下错误

错误:[writeRaster] 无法打开文件:C:/Users/nn/Desktop/lyr.1 另外:警告信息: C:/Users/nn/Desktop/lyr.1:没有这样的文件或目录(GDAL错误4)

我希望使用以下函数在 raster 包中提供相同的输出

raster::writeRaster(s, names(s), bylayer=TRUE, format='GTiff', overwrite=TRUE)

【问题讨论】:

    标签: r r-raster terra


    【解决方案1】:

    你必须做更多的工作

    dir.create("test")
    setwd("test")
    f <- paste0("test", 1:nlyr(s), ".tif")
    r <- writeRaster(s, f, overwrite=TRUE)
    list.files()
    # [1] "test1.tif" "test2.tif" "test3.tif"
    
    r
    #class       : SpatRaster 
    #dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
    #resolution  : 36, 18  (x, y)
    #extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
    #sources     : test1.tif  
    #              test2.tif  
    #              test3.tif  
    #names       :      lyr.1,      lyr.1,      lyr.1 
    #min values  : 0.02075680, 0.01058152, 0.02179740 
    #max values  :  0.9874134,  0.9990475,  0.9883418 
    

    这也有效:

    names(s) <- c("a", "b", "c")
    x <- writeRaster(s, names(s), overwrite=TRUE, filetype="GTiff")
    

    但请注意文件名没有 tif 扩展名

    sources(x)
    #    source nlyr
    #1 ./test/a    1
    #2 ./test/b    1
    #3 ./test/c    1
    

    所以我会这样做

    z <- writeRaster(s, paste0(names(s), ".tif"), overwrite=TRUE)
    
    #class       : SpatRaster 
    #dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
    #resolution  : 36, 18  (x, y)
    #extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
    #sources     : a.tif  
    #              b.tif  
    #              c.tif  
    #names       :          a,          b,          c 
    #min values  : 0.02075680, 0.01058152, 0.02179740 
    #max values  :  0.9874134,  0.9990475,  0.9883418 
    

    错误消息现已改进(请参阅this issue

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 2021-02-06
    • 2022-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多