问题
I am working on NOAA AVHRR daily Sea Surface Temperature (SST) data of 31 years. The data is in NetCDF format with dimensions as 28 (lon) x 40 (lat) x 11686(days). I am supposed to compute monthly climatological mean (e.g. mean of all Januaries of 31 years and so on). Using ncdf4 and chron libraries I was able to get it in array form.
ncin <- nc_open('sstfile.nc')
sst_array <- ncvar_get(ncin, 'sst')
Since time variable is separate from SST data, I had to use it loop over the array.
is.leapyear <- function(year){
return(((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0))
}
dateseq <- seq(as.Date("1987-01-01"), as.Date("2018-12-31"), by=1)
Using raster library I am converting to rasters and then doing computation.
for ( i in seq(11686)) {
dtft <- strsplit(as.character(as.Date(dateseq[i])), split = '-')
y <- as.integer(dtft[[1]][1])
m <- as.integer(dtft[[1]][2])
d <- as.integer(dtft[[1]][3])
while (m == 1){
assign(paste0('r',y,'.',d), raster(matrix(sst_array[1:27, 1:38, i],
nrow = 27, ncol = 38)))
m = m + 1
}
if (is.leapyear(y) == TRUE) (i = i + 366)
else (i = i + 365)
}
Problem is it's creating far too many rasters and first computing monthly mean and then yearly.
r87jan <- stack(mget(paste0('r1987.',1:31)))
r87janmean <- calc(r87jan, mean)
Is there any function/method which can compute over this time duration without making so many rasters and computation can remain as array or a matrix? Or can the above code can be improved to compute the monthly mean for all years at once?
回答1:
You do not provide your data, but I think you can do something like this:
library(raster)
nc <- brick('sstfile.nc')
dates <- getZ(nc)
months <- as.integer(format(dates, "%m"))
s <- stackApply(nc, months, fun=mean)
回答2:
If I can offer an answer not in R, if you have cdo (climate data operators installed) you can simply do this on the linux command line:
cdo ymonmean sstfile.nc sst_climate.nc
the file sst_climate.nc will contain 12 timesteps, with the average of all the January, Feb and so on...
You can install cdo easily in, say, ubuntu/mint with
sudo apt-get install cdo
and you can also install ubuntu easily within Windows 10 these days to access these useful tools easily. Documentation is available here https://code.mpimet.mpg.de/projects/cdo/
来源:https://stackoverflow.com/questions/54821567/estimating-monthly-climatology-on-netcdf-data-using-r