如何从 R 中特定位置的 NetCDF 文件中提取表面风速数据?

问题描述

我正在尝试为基础设施获取风能。我有一个包含它们的纬度和经度的数据集。

NetCDF 文件给出了 2058 年的每日近地表风速数据预测。可以通过以下 URL 下载:http://esg-dn2.nsc.liu.se/thredds/fileServer/esg_dataroot1/cmip6data/CMIP6/ScenarioMIP/EC-Earth-Consortium/EC-Earth3/ssp585/r1i1p1f1/day/sfcWind/gr/v20200310/sfcWind_day_EC-Earth3_ssp585_r1i1p1f1_gr_20580101-20581231.nc

我尝试了以下循环来获取每个位置(最近的网格点)的平均风速:

sfcWind_filepath<-paste0("sfcWind_day_EC-Earth3_ssp585_r1i1p1f1_gr_20580101-20581231.nc")
sfcWind_output<-nc_open(sfcWind_filepath)

lon<-ncvar_get(sfcWind_output,varid = "lon")
lat<-ncvar_get(sfcWind_output,varid = "lat")
sfcWind_time<-nc.get.time.series(sfcWind_output,v = "sfcWind",time.dim.name = "time")

sfcWind<-ncvar_get(sfcWind_output,"sfcWind")

for(i in 1:nrow(Infrast))
{sfcWind<-rep(i,nrow(Infrast))
x<-Infrast[i,4]
y<-Infrast[i,3]
Infrast[i,12]<-mean(sfcWind[which.min(abs(lon - (x))),which.min(abs(lat - (y))),c(which(format(sfcWind_time,"%Y-%m-%d") == "2058-01-01"):which(format(sfcWind_time,"%Y-%m-%d") == "2058-12-31"))])
}

其中 Infrast 是我的基础设施数据集,它们的纬度在第 3 列,经度在第 4 列,我希望输出保存在我的数据集的第 12 列。

我收到以下错误

Error in sfcWind[which.min(abs(lon - (x))),: 
  incorrect number of dimensions

我之前使用此代码来获得预计温度的平均值,并且效果很好。 NetCDF 文件具有与此相同的维度(纬度、经度、时间)。这就是为什么我不明白这里的错误

我对 R 很陌生,我刚刚开始使用 NetCDF 文件,任何帮助或建议将不胜感激。

解决方法

注意,我无法对此进行测试,因为没有提供可重现的示例。 尽管如此,这应该有效。

首先将文件作为光栅砖打开

library(raster)
sfcWind_output <- brick(sfcWind_filepath,varname="sfcWind")

现在您可以使用这样的坐标提取值

extract(sfcWind_output,cbind(lon,lat))