合并R中的netCDF文件 [英] Merge netCDF files in R
问题描述
我有2个netCDF文件(每个.nc文件有4个变量:易感,已感染,已恢复和可居住.每个变量的尺寸为64 x 88).我想将这2个文件合并为一个netCDF文件,这样合并后的文件将分别从2个文件中堆叠,从2个文件中感染,从2个文件中恢复和从2个文件中可居住.
I have 2 netCDF files (each .nc file has 4 variables: Susceptible, Infected, Recovered and Inhabitable. The dimension of each variable is 64 x 88). I would like to merge these 2 files into a single netCDF file such that the merged file will stack separately Susceptible from the 2 files, Infected from the 2 files, Recovered from the 2 files and Inhabitable from the 2 files.
有人可以帮我吗?
预先感谢, 阿肖克
推荐答案
ncdf4
包将完成您想做的事情.看看下面的代码,仅是一个变量的示例.
The ncdf4
package will do what you want to do. Have a look at the code below, example for one variable only.
#install.packages('ncdf4')
library(ncdf4)
file1 <- nc_open('England_aggr_GPW4_2000_0001.nc')
file2 <- nc_open('England_aggr_GPW4_2000_0002.nc')
# Just for one variable for now
dat_new <- cbind(
ncvar_get(file1, 'Susceptible'),
ncvar_get(file2, 'Susceptible'))
dim(dat_new)
var <- file1$var['Susceptible']$Susceptible
# Create a new file
file_new3 <- nc_create(
filename = 'England_aggr_GPW4_2000_new.nc',
# We need to define the variables here
vars = ncvar_def(
name = 'Susceptible',
units = var$units,
dim = dim(dat_new)))
# And write to it
ncvar_put(
nc = file_new,
varid = 'Susceptible',
vals = dat_new)
# Finally, close the file
nc_close(file_new)
更新:
另一种方法是使用栅格数据包,如下所示.我没有弄清楚如何制作4D栅格堆栈,因此我将每个变量将数据拆分为一个NCDF
文件.这样对您有用吗?
Update:
An alternative approach is using the raster package as shown below. I didn't figure out how to make 4D raster stacks, so I am splitting your data into one NCDF
file per variable. Would that work for you?
#install.packages('ncdf4')
library(ncdf4)
library(raster)
var_names <- c('Susceptible', 'Infected', 'Recovered', 'Inhabitable')
for (var_name in var_names) {
# Create raster stack
x <- stack(
raster('England_aggr_GPW4_2000_0001.nc', varname = var_name),
raster('England_aggr_GPW4_2000_0002.nc', varname = var_name))
# Name each layer
names(x) <- c('01', '02')
writeRaster(x = x,
filename = paste0(var_name, '_out.nc'),
overwrite = TRUE,
format = 'CDF')
}
这篇关于合并R中的netCDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!