如何访问API调用返回的NetCDF文件?

How to access the NetCDF file returned by an API call?

提问人:talocodat 提问时间:11/17/2023 最后编辑:talocodat 更新时间:11/17/2023 访问量:37

问:

我有这个 API 请求:https://dataset.api.hub.geosphere.at/v1/grid/historical/inca-v1-1h-1km?parameters=RR&parameters=T2M&parameters=UU&parameters=VV&parameters=RH2M&start=2014-01-01&end=2014-02-01&bbox=47.25392576%2C11.34458542%2C47.278834%2C11.44352138&output_format=netcdf&filename=file_try

我使用以下代码在 R 中获取数据:

link <- "https://dataset.api.hub.geosphere.at/v1/grid/historical/inca-v1-1h-1km?parameters=RR&parameters=T2M&parameters=UU&parameters=VV&parameters=RH2M&start=2014-01-01&end=2014-02-01&bbox=47.25392576%2C11.34458542%2C47.278834%2C11.44352138&output_format=netcdf&filename=file_try"

data <- httr::GET(link) %>% 
    httr::content()

我的问题是获取NetCDF文件。在 API 文档中,它说:content-type: application/x-netcdf。到目前为止,我收到一个格式为“raw”的对象。我想解决方案在于content()函数,但我不知道在这里指定什么。我认为 NetCDF 文件作为 R 对象从来都不是安全的,而是从硬盘驱动器访问的,这就是为什么这不起作用。

调用download.file(link)会是更好的选择吗?这里的问题是 ncdf4 无法识别下载的文件(R_nc4_open错误:NETCDF:未知文件格式)。对我来说,该文件似乎具有“双”文件名,因为我在 API 请求中(在最后)和另外在 download.file(destfile=...) 中指定了文件名。 任何帮助都值得赞赏!

r netcdf httr

评论


答:

0赞 I_O 11/17/2023 #1

您可以(如果您只想临时下载)这样做:

the_tempfile <- tempfile() ## create a temporary file

download.file(link,
              destfile = the_tempfile,
              mode = "wb" ## save as BINARY
              )

检查(使用,例如 {ncdf4})

library(ncdf4)

nc_open(the_tempfile)

评论

0赞 talocodat 11/18/2023
这不起作用:nc_open(the_tempfile)中的错误:nc_open尝试打开文件C:\ Users \ me \ AppData \ Local\ Temp \ Rtmpi07Rb7 \ file33e4358125dd时出错(return_on_error= FALSE)