Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
A while back I wrote a blog post on the R package I wrote for reading and manipulating grads data. The library is quite basic, and does not support a number of grads data file options:
- Using one ctl file, and multiple binary files
- Some variables have only one vertical level
When I faced data that had these properties, I had a choice to either expand my readGrads
library, or convert the data to some other format which was easier to read into R. I chose to convert the data to NetCDF and then reading it using the excellent ncdf library. Luckily I did not have to write a grads to NetCDF conversion tool myself, but I used the cdo tool. This program is “a collection of command line Operators to manipulate and analyse Climate and NWP model Data” (quote from the website). Converting a grads file to NetCDF can be done using the following command:
cdo -f nc import_binary in_grads.ctl out_ncdf.nc
As I wanted to perform this conversion from within R, I created a function which uses cdo through a system call. The grads2nc
function looks like:
grads2nc = function(ctl_input, nc_output, verbose = TRUE) { if(Sys.which("cdo")[[1]] == "") stop("cdo executable not found. Check PATH or install cdo.") if(verbose) ext = "" else ext = "> /dev/null" cmd = sprintf("cdo -f nc import_binary %s %s %s", ctl_input, nc_output, ext) t = system.time(ret_code <- system(cmd)) if(verbose & (ret_code != 127)) { message(sprintf("Processing \"%s\" to \"%s\" is done, time spent:", ctl_input, nc_output)) print(t) } else { stop("Conversion of grads file to nc failed") } return(invisible(ret_code)) }
With this function loaded into the R session, the conversion can be performed using:
> grads2nc("output/attm400.ctl", "output/test.nc") cdo import_binary: Processed 41 variables. ( 2.50s ) Processing "output/attm400.ctl" to "output/test.nc" is done, time spent: user system elapsed 1.765 0.760 3.642
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.