【问题标题】:R function stops after system() callR函数在system()调用后停止
【发布时间】:2024-04-28 22:25:01
【问题描述】:

我在 R 中围绕 GDAL 编写了一个非常简单的包装器。它利用预先编写的语句传递给系统,创建一个输出,然后我想再次将其读入 R 环境。

它的工作原理是在工作目录中创建一个临时目录,打印出我们感兴趣区域的 ESRI 形状文件,然后通过此切割光栅,并带有一些预设信息。

我的问题:成功运行 system() 调用并创建输出文件后,函数停止。它不会执行下一次调用并将输出读入 R 环境。

gdalwarpwarp <- function(source_file, source_srs, newfilename, reread=TRUE, clean=TRUE, cutline){

  #Create tempfolder if it doesn't exist in the working directory.
  if (!dir.exists("./tempfolder")){
    dir.create("./tempfolder")
  }

  #Write temporary shape file
  terra::writeVector(cutline, filename = "./tempfolder/outline_AOI.shp" , filetype='ESRI Shapefile',overwrite=TRUE)

  #Warp!

  if(reread==FALSE){
    system(paste0("gdalwarp -cutline ./tempfolder/outline_AOI.shp -dstnodata -9999 -s_srs EPSG:3006 ",source_file, " ",paste0("./tempfolder/",newfilename)))
    message('warp warped TRUE')

  } else if(reread==TRUE){
    system(paste0("gdalwarp -cutline ./tempfolder/outline_AOI.shp -dstnodata -9999 -s_srs EPSG:3006  ",source_file, " ",paste0("./tempfolder/",newfilename)))
    newfilename <- terra::rast(paste0("./tempfolder/",newfilename))
  }

}

这不会运行:

newfilename <- terra::rast(paste0("./tempfolder/",newfilename))

【问题讨论】:

  • 不需要if(reread==TRUE) 部分,您已经拥有else
  • 你怎么知道该行没有被执行? R 函数应始终具有明确的返回值。你的没有。
  • 我可以看到在temp文件夹中创建了输出.tif文件,但它没有再次读入R环境。我可以选择吗?返回(新文件名)?或返回(消息(“完成”))
  • 现在我明白了!环境被废弃而不返回我的输出。谢谢!我会删除这个问题以避免混淆。

标签: r function system gdal


【解决方案1】:

函数没有返回任何东西。这是您的功能的一些改进版本。如果要保留输出,提供完整路径会更有意义,而不是将其保存到临时文件夹。我还注意到您没有使用参数source_srs

gdalwarpwarp <- function(source_file, source_srs, newfilename, reread=TRUE, clean=TRUE, cutline){

  #Write temporary shape file
  shpf <- file.path(tempdir(), "aoi.shp")
  terra::writeVector(cutline, filename = shpf, filetype='ESRI Shapefile',overwrite=TRUE)

   outf <- file.path(tempdir(), newfilename)
    system(paste0("gdalwarp -cutline shpf -dstnodata -9999 -s_srs EPSG:3006 ",source_file, " ", outf)
   
    if (reread) {
        terra::rast(outf)
    } else {
       message('warp warped TRUE')
       invisible(filename)
    }
}

我想知道你为什么不使用terra::resampleterra::project;可能在mask 之前或之后(我可能不明白使用cutline 的好处。

【讨论】:

  • 这非常接近最终结果。添加 GDAL 命令-crop_to_cutline 时更有意义。这可能也可以在 terra 中进行吗?您对 source_srs 是正确的,我最终没有使用它。我也删除了干净。