R 函数在 system() 调用后停止

R function stops after system() call

我在 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))

函数没有return任何东西。这是您的功能的改进版本。如果您想保留输出,提供完整路径比将其保存到临时文件夹更有意义。我还注意到您没有使用参数 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.

的好处