Converting grads files to NetCDF from within R using CDO

January 30, 2012
By

(This article was first published on NumberTheory » R stuff, and kindly contributed to R-bloggers)

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

To leave a comment for the author, please follow the link and comment on his blog: NumberTheory » R stuff.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , , ,

Comments are closed.