0

I am a user of R and would like some help in the following: I have two netcdf files (each of dimensions 30x30x365) and one more with 30x30x366. These 3 files contain a year's worth of daily data, where the last dimension refers to the time dimension. I wanted to combine them separately i.e. I wanted the output file to contain 30x30x1096.

Note: I have seen a similar question but the output results in an average (i.e. 30x30x3) which I do not want.

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86
Keegan C
  • 3
  • 5
  • 1
    Possible duplicate of [Merge netCDF files in R](https://stackoverflow.com/questions/45096730/merge-netcdf-files-in-r) – divibisan Mar 15 '19 at 21:14

2 Answers2

2

from the comment I see below you seem to want to merge 3 files in the time dimension. As an alternative to R, you could do this quickly from the command line using cdo (climate data operators):

cdo mergetime file1.nc file2.nc file3.nc mergedfile.nc

or using wildcards:

cdo mergetime file?.nc mergedfile.nc

cdo is easy to install under ubuntu:

sudo apt install cdo 
ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86
1

Without knowing exactly what dimensions and variables you have, this may be enough to get you started:

library(ncdf4)

output_data <- array(dim = c(30, 30, 1096))
files <- c('file1.nc', 'file2.nc', 'file3.nc')
days <- c(365, 365, 366)

# Open each file and add it to the final output array
for (i in seq_along(files)) {
    nc <- nc_open(files[i])
    input_arr <- ncvar_get(nc, varid='var_name')
    nc_close(nc)

    # Calculate the indices where each file's data should go
    if (i > 1) {
        day_idx <- (1:days[i]) + sum(days[1:(i-1)])
    } else {
        day_idx <- 1:days[i]
    }

    output_data[ , , day_idx] <- input_arr
}

# Write out output_data to a NetCDF. How exactly this should be done depends on what
# dimensions and variables you have.

# See here for more:
#   https://publicwiki.deltares.nl/display/OET/Creating+a+netCDF+file+with+R
C. Braun
  • 5,061
  • 19
  • 47
  • @ C. Braun I forgot to mention, the file names are file1.nc, file 2.nc and file3.nc. The variable name is 'sst' where 30x30 are longitude x latitude and 365/366 indicate days. Could you please update? (I'm actually a beginner here) – Keegan C Mar 15 '19 at 20:39