从r中两个具有最高和最低温度的netcdf中创建以平均温度为变量的新netcdf



我有两个具有相同特征(晚、长、时间段)的netcdf文件,一个以最高温度为变量,另一个以最低温度为变量。我想创建一个新的netcdf文件完全像原来的,但不是最高和最低温度,我需要平均温度作为变量。我对R和操纵netcdf文件很陌生,我将非常感谢任何帮助!我需要计算平均值的代码和两个文件都在这个链接上。唯一的代码在此文本下方。代码工作正常,但生成的netcdf文件不正确(尺寸等不同)。

非常感谢!

# Compute mean
library(ncdf4)
library(raster)
library(rgdal)
library(lubridate)
library(geosphere)
library(reshape2)
library(ggplot2)
setwd("~/")
nc_max <- nc_open('Obs_tas_max_1983-2005.nc')

nc_min <- nc_open('Obs_tas_min_1983-2005.nc')

X <- list()
h <- 1
lat <- ncvar_get(nc_max, "lat");
nlat <- nrow(lat)
lon <- ncvar_get(nc_max, "lon");
nlon <- nrow(lon)
# lat <- as.vector(lat);
# lon <- as.vector(lon)
t_max <- ncvar_get(nc_max, "tas_max");
t_min <- ncvar_get(nc_min, "tas_min");
tas <- (t_max+t_min)/2
sw <- as.character('tas_max')
time <- ncvar_get(nc_max, "time");
ndays <- length(time)
v <- matrix(NA, length(lat), ndays)

# for (t in 1:ndays) {
#     x <- ncvar_get(nc_max, sw, start = c(1, 1, t), count = c(nlon, nlat, 1))
#     x <- as.vector(x)
#     v[ ,t] <- x

X[[h]] <- (v)
# h <- h + 1
# nc_close(nc_max)
# nc_close(nc_min)

X <- do.call(rbind, X) # Time on the rows, coordinates on the columns
dt <- seq.Date(as.Date("1983-01-01"), as.Date("2005-12-31"), 'day')

m <- month(dt)
d <- day(dt)
idx <- !(m == 2 & d == 29)
X <- X[idx, ]

dim_idx <- ncdim_def(name='Index',
units='m',
longname='idx',
vals= 1:nrow(X))

dim_time <- ncdim_def('time',
units='days from 1983-01-01',
longname='time',
calendar="standard", vals=1:idx)

varLat <- ncvar_def(name='lat',
units='degrees_north',
dim=list(dim_idx),
missval=NA,
longname='latitude',
prec='double'
)

varLon <- ncvar_def(name='lon',
units='degrees_east',
dim=list(dim_idx),
missval=NA,
longname='latitude',
prec='double'
)

varX <- ncvar_def(name='tas',
units= 'degrees Celsius',
dim=list(dim_time, dim_idx),
missval=NA,
longname='Temperature'
)

vars <- list(varLat, varLon, varX)

outputfile <- paste('tas', '.nc', sep = '_')

con <- nc_create(outputfile, vars)
ncvar_put(con, varLat, lat)
ncvar_put(con, varLon, lon)
ncvar_put(con, varX, X)

nc_close(con)

我知道你在要求R帮助,但我认为这可能在几行代码中完成。像这样:

# change variable name to be the same in each netcdf file
ncrename -v tas_max,tas Obs_tas_max_1983-2005.nc tmax.nc
ncrename -v tas_min,tas Obs_tas_min_1983-2005.nc tmin.nc
# ensemble average of tas variable across the two files
ncea tmax.nc tmin.nc tas_out.nc
# change the long_name attribute
ncatted -O -a long_name,tas,o,c,Temperature tas_out.nc

最新更新