Merge netCDF files in R

后端 未结 1 881
死守一世寂寞
死守一世寂寞 2020-12-16 07:33

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 the

1条回答
  •  伪装坚强ぢ
    2020-12-16 07:50

    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')
    }
    

    0 讨论(0)
提交回复
热议问题