I have 3 NetCDF files containing data on the average daily temperature range (dtr) per month between 1981 and 2010. A file covers a period of 10 years, so each pixel has 10 x 12 values (1 value per month x 10 years). The files can be downloaded here (a login is required).
I would like to merge all these files into a single one containing the monthly mean dtr for the entire period covered by the 3 files. The idea is to end up with 12 values per pixel (1 average monthly value for 30 years).
I have no previous experience working with NetCDF format and don't really understand its structure. I tried the NetCDF
function from the ncdump
package but I did not learn much from it…
Unfortunately, doing the following only compute the mean dtr in 30 years.
"GIS/Clim/BioClim/dtr/" %>%
list.files(pattern = "\\.nc$", full.names = TRUE) %>%
raster::stack() %>%
raster::overlay(fun = mean)
Here is what I get when I extract the data from a single pixel in one file:
library(tidyverse)
library(sf)
p <- tibble(lat = 45.76, lon = -107.12) %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326)
raster::stack("GIS/Clim/dtr/cru_dtr-2001_2010.nc") %>%
raster::extract(p, df = TRUE)
# X2001.01.16 X2001.02.15 X2001.03.16 X2001.04.16 X2001.05.16 X2001.06.16
# 1 11.1 11.3 10.8 9.900001 9.800000 9.400001
# X2001.07.16 X2001.08.16 X2001.09.16 X2001.10.16 X2001.11.16 X2001.12.16
# 1 10.100000 8.6 10.200000 9.500000 9.5 9.3
# X2002.01.16 X2002.02.15 X2002.03.16 X2002.04.16 X2002.05.16 X2002.06.16
# 1 10.6 10.7 10.3 9.0 9.600000 9.1
#
# ... ... ...
#
# X2010.07.16 X2010.08.16 X2010.09.16 X2010.10.16 X2010.11.16 X2010.12.16
# 1 9.000000 9.0 8.900001 8.800000 8.3 8.3
How could I combine these 3 NetCDF files and compute the monthly mean dtr to create a new NetCDF?
Note that a Python solution also works for me.
Difficult to answer as you do not provide some simple example data. But it would be something along these lines
library(raster)
filenames <- c("one.nc", "two.nc", "three.nc")
b <- lapply(filenames, brick)
s <- stack(b)
m <- stackApply(s, 1:12, mean)