在targets流水线中使用terra加载栅格数据遇外部指针无效错误
问题
尝试在targets流水线中使用terra包加载栅格数据,对应的_targets.R文件代码如下:
# Created by use_targets(). # Follow the comments below to fill in this target script. # Then follow the manual to check and run the pipeline: # https://books.ropensci.org/targets/walkthrough.html#inspect-the-pipeline # nolint # Load packages required to define the pipeline: library(targets) # library(tarchetypes) # Load other packages as needed. # nolint # Set target options: tar_option_set( packages = c( "tidyverse", "terra", ), # packages that your targets need to run format = "rds" # default storage format # Set other options as needed. ) # tar_make_clustermq() configuration (okay to leave alone): options( clustermq.scheduler = "multiprocess" ) # tar_make_future() configuration (okay to leave alone): # Install packages {{future}}, {{future.callr}}, and {{future.batchtools}} to allow use_targets() to configure tar_make_future() options. # Run the R scripts in the R/ folder with your custom functions: tar_source() # source("other_functions.R") # Source other scripts as needed. # nolint # Replace the target list below with your own: list( ## Load all data in R/load_data.R tar_target(esg_rast_file, "data/ESGs/ESGs.tif", format="file"), tar_target(esg_rast_data, terra::rast(esg_rast_file)) )
运行tar_make()后的输出如下:
r$> library(targets) r$> tar_make() • start target esg_rast_file • built target esg_rast_file [6.42 seconds] • start target esg_rast_data • built target esg_rast_data [0.05 seconds] • end pipeline [7.96 seconds] r$> tar_load(esg_rast_data) NULL value passed as symbol address r$> esg_rast_data class : SpatRaster Error in x@ptr$nrow() : external pointer is not valid
这是正常现象吗?是否存在操作错误?同时加载sf的.shp数据也遇到了类似问题,似乎遗漏了关键步骤。
解决方案
- 问题核心:
terra的SpatRaster和sf的空间对象依赖外部指针,默认的rds格式无法正确序列化/反序列化这类对象,导致加载后指针失效。 - 修正步骤:
- 对于
terra栅格数据:将目标的存储格式改为"terra",这是targets专为SpatRaster设计的格式,能正确处理外部指针。 - 对于
sf矢量数据:同理,将目标格式改为"sf"。
- 对于
- 修改后的
_targets.R关键部分:
list( tar_target(esg_rast_file, "data/ESGs/ESGs.tif", format="file"), # 为terra栅格指定format="terra" tar_target(esg_rast_data, terra::rast(esg_rast_file), format="terra") )
- 补充说明:
- 若流水线中多数是同类型空间对象,也可以在
tar_option_set()中全局设置格式,比如tar_option_set(format = "terra")。 - 重新运行
tar_make()后,再用tar_load(esg_rast_data)即可正常加载和使用栅格对象。
- 若流水线中多数是同类型空间对象,也可以在
内容的提问来源于stack exchange,提问作者Mike Schmidt
相关产品推荐
相关产品推荐

