Merge netCDF files in R

2019-04-02 07:13发布

问题:

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.

Here are the 2 files(first and second)

Could anyone help me with this please?

Thanks in advance, Ashok

回答1:

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)

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