R/readGAEZ.R

Defines functions readGAEZ

### read GAEZ slope dataset
## this function should be able to read all the different GAEZ datasets
#'@importFrom raster stack extent<- extent projection<- setZ nlayers

readGAEZ <- function(types=c("cultivated land", "grassland & woodland"), res=NULL) {
  

    ## list all files that can potentially be loaded
    
    files <- as.list(list.files(paste0(geodata$config$mainfolder, "/GAEZ/"), pattern = ".tif$", full.names = T, ignore.case = F, recursive = T))
    names(files) <- gsub("([a-z])/.*", "\\1", list.files(paste0(geodata$config$mainfolder, "/GAEZ/"), pattern = ".tif$", full.names = F, ignore.case = F, recursive = T))
    
    # select a certain file type
    
    if ((!is.null(types)) & all(types %in% names(files))) {
      files <- files[names(files) %in% types]
    } else {
      cat("Select one or several type(s). Available types are: ", paste0(names(files),collapse = "''") )
    }
    
    # if(is.numeric(years)) {
    #   # only select files that contain years
    #   files <- files[gsub(".*([0-9]{4}).*","\\1",(filenames)) %in% years]
    #   if (!all(is.element(years, gsub(".*([0-9]{4}).*","\\1",(filenames))))) stop("Data for the specified years not available")  
    # }
    
    dat <- stack(files)
    names(dat) <- names(files)
    extent(dat) <- round(extent(dat), digits=3) # round away small extent errors: e.g. 179.999
    projection(dat) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
    
    
    ## the function should consider the right aggregation method for the different types
    if(!is.null(res)) {
      fact <- res/res(dat)
      if(any(fact<1)) stop("resolution has to be bigger than 0.08333333, e.g. 0.5")
      dat <- raster::aggregate(dat, fact=fact, fun=sum, expand=F)
    }
  
  setZ(dat, rep(as.Date("2000-01-01"), nlayers(dat)))
  #setZ(dat, rep(2000, nlayers(dat)))
  
  #   attr(tmp, "unit") <- "km2"
  
return(dat)
}
pik-piam/geodata documentation built on Nov. 5, 2019, 12:21 a.m.