R/LoadCMIP.R

#' Load CMIP5 Data into R from NetCDF.
#'
#' @param filepath The filepath to the directory containing the files.
#' @param recursive A logical indicating wether list.files() is recursive.
#' @return An array with dimensions \code{dim = c(model, member, longitude, latitude, time)}.
#' @examples
#' LoadCMIP("rcp85/tasmin", variable = "tasmin")
#'
# Function to read CMIP5 data from netcdf files
library(ncdf4)
library(raster)
library(parallel)
exp_filepath <- "/home/Earth/ahunter/CMIP5/tasmin/rcp85/nh"
obs_filepath <- "/home/Earth/ahunter/CMIP5/tasmin/historical/nh"

LoadCMIP <- function(filepath = NULL, recursive = TRUE, variable = NULL) {
  if (is.null(filepath)) {
    stop("'filepath' must be specified")
  }
  if (is.null(variable)) {
    stop("'variable' must be specified")
  }

  files <- list.files(filepath, full.names = TRUE)
  nmodels <- length(files)
  test <- nc_open(files[1])
  lon1 <- ncvar_get(test, "lon")
  nlon <- length(lon1)
  lat1 <- ncvar_get(test, "lat")
  nlat <- length(lat1)
  time1 <- ncvar_get(test, "time")
  ntime <- length(time1)
  model <- list()
  cmip_data <- list()

  for (i in 1:length(files)) {
    cmip <- nc_open(files[i])
    model[i] <- cmip$filename
    cmip_data <- apply(files, MARGIN = 1, FUN = ncvar_get(nc_open(files))
    cmip_data[[i]] <- as.array(ncvar_get(cmip, variable))
  }
  invisible(result <- list(data = cmip_data, metadata = model))
}
alasdairhunter/EuropeanRiskIndex documentation built on May 10, 2019, 8:50 a.m.