R save as NetCDF file after simple calculation

732 Views Asked by At

I want to do something (apparently) simple, but didn't yet find the right way to do it:

I read a netcdf file (wind speed from the ERA5 reanalysis) on a grid. From this, I use the wind speed to calculate a wind capacity factor (using a given power curve). I then want to write a new netcdf file, with exactly the same structure as the input file, but just replacing the input wind speed by the new variable (wind capacity factor).

Is there a simple/fast way to do this, avoiding to redefine all the dims, vars ... with ncvar_def and ncdim_def ?

Thanks in advance for your replies!

1

There are 1 best solutions below

4
On

Writing a netcdf file in R is not overly complicated, there is a nice example online here:

http://geog.uoregon.edu/GeogR/topics/netCDF-write-ncdf4.html

You could copy the dimensions from the input file.

However if your wind power curve is a simple analytical expression then you could perform this task in one line from the command line in bash/linux using climate data operators (cdo).

For example, if you have two variables 10u and 10v in the file (I don't recalled the reanalysis names exactly) then you could make a new variable WCF=SQRT(U2+V2) in the following way

cdo expr,'wcf=sqrt(10u**2+10v**2)' input.nc output.nc 

See an example here:

https://code.mpimet.mpg.de/boards/53/topics/1622

So if your window power function is an analytical expression you can define it this way without using R at all or worrying about dimensions etc, the new file will have an variable wcf added. You should then probably use NCO to alter the metadata (units etc) to ensure they are appropriate.