R/countryFunRast.R

Defines functions countryFunRast

Documented in countryFunRast

## export values on country level from a raster dataset
##
## major improvement would be if for country it was defined once which cells belong to it and data is accessed this way then



library(rgdal)
library(maptools)
library(utils)




#' Return function values per country
#' 
#' Returns values per country based on the function and the countries
#' boundaries. Is based on the extract function from the raster package.
#' 
#' 
#' @usage countryFunRast(x, fun=sum, countries="DIVA GIS", cache=T)
#' @param x Raster file where function is applied to
#' @param fun Function that is applied to the raster values. E.g. 'sum' sums up
#' raster values per country
#' @param countries Dataset that is used to sperate between counties. Currently
#' only polygons from 'DIVA GIS' supported
#' @param cache If TRUE, will read the countries boundaries from cache if
#' available
#' @return magpie object with the values per country
#' @author Ulrich Kreidenweis
#' @seealso \code{\link{countryCellRast}}
#' @examples
#' 
#' \dontrun{countryFunRast()}
#' 
#' @export countryFunRast
#' @importFrom magclass magpiesort as.magpie
countryFunRast <- function(x, fun=sum, countries="DIVA GIS", cache=T) {
  
  boundaries <- readCountries(countries = countries, cache=cache)
  
  dat <- raster::extract(x, boundaries, fun=fun, na.rm=T, df=T)
  dat$ISO <- sapply(slot(boundaries, "polygons"), function(i) slot(i, "ID"))
  dat <- magpiesort(as.magpie(dat[,c("ISO","layer")], spatial=1))

  return(dat)
  
}
pik-piam/geodata documentation built on Nov. 5, 2019, 12:21 a.m.