将NetCDF作为栅格堆栈读入R

qpgpyjmq  于 2023-05-20  发布在  Etcd
关注(0)|答案(1)|浏览(112)

我有两个NetCDF文件,涵盖了两个不同时间段(1:2035-2054,2:2055-2074)的相同变量(hurs)的测量。我想将这些作为光栅堆栈读入R,并提取时间段2041-2070所有文件都有以下时间单位:parent_time_units:1850-1-1 00:00:00数据以月分辨率显示。这是怎么做到的?
我已经尝试了一个循环,将两个文件合并到光栅堆栈中。但我不知道如何提取时间段。这就是我到目前为止所做的:

library(raster)

# List of file names
file_names <- c("hurs_Amon_MPI-ESM1-2-LR_ssp126_r10i1p1f1_gn_203501-205412.nc","hurs_Amon_MPI-ESM1-2-LR_ssp126_r10i1p1f1_gn_205501-207412.nc")

#Initialize the output stack
output_stack <- stack()

# Loop over the files and stack them into the output stack
for (file_name in file_names) {
  data <- raster(file_name)
  output_stack <- stack(output_stack, data)
}

# Print the output stack
print(output_stack)

结果如下:

> # Print the output stack
> print(output_stack)
class      : RasterStack 
dimensions : 96, 192, 18432, 2  (nrow, ncol, ncell, nlayers)
resolution : 1.875, 1.864677  (x, y)
extent     : -0.9375, 359.0625, -89.50451, 89.50451  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
names      : Near.Surface.Relative.Humidity.1, Near.Surface.Relative.Humidity.2

现在我被卡住提取所需的时间段。

r3i60tvu

r3i60tvu1#

您可以使用terra R包代替raster,它的速度要快得多,如

library(terra)

#Create a list of .nc files
files <- list.files(path = getwd(), #In place of `getwd()`, you can provide the directory containing .nc files
                    pattern = "\\.nc$", full.names = TRUE)

# stack rasters
output_stack <- rast(files)

相关问题