### to do
# needs thorough checking whether it does what it should
# auto detection of years is not very elegant at the moment. First it trys to detect. If it has done then there is a 2. loop that does the replacement in this case
# add functionality for lists
#
#' Convert raster data to MAgPIE object
#'
#' Raster data (layers, bricks or stacks) from the raster package is converted
#' to a MAgPIE object. In the case of bricks and stacks different data
#' dimensions are created for the different layers. Data should be in lat/long
#' with a 0.5x0.5 degree resolution, and have at least the extent of MAgPIE
#' data (-180,180,-56,83.5)
#'
#'
#' @usage raster2magpie(x, detect_years=TRUE)
#' @param x A raster object
#' @param detect_years The function can try to detect years (4 digit numbers)
#' in the names of the raster, and use them as the temporal dimension
#' @return A MAgPIE object with the data of the raster at the geographic center
#' of each MAgIE cell
#' @author Ulrich Kreidenweis
#' @examples
#'
#' \dontrun{
#' r <- raster::raster()
#' raster::res(r) <- 0.5
#' raster::values(r) <- 1:(raster::ncell(r))
#' m <- raster2magpie(r)
#' head(m)
#' }
#'
#' @export raster2magpie
#' @importFrom raster res couldBeLonLat
#' @importFrom magclass new.magpie
raster2magpie <- function(x, detect_years=TRUE) {
# if(class(x)!="RasterLayer") stop("x has to be a RasterLayer")
if(any(res(x) != 0.5)) warning ("Raster resolution should be 0.5 x 0.5, if it is not only information from the center of MAgPIE cells will be considered")
if(!couldBeLonLat(x, warnings=F)) stop("Raster has to be in long/lat")
## try to detect years in the names. But be careful, that the data is then filled to the magpie object correctly!!
# requirements
years <- NULL
names <- names(x)
dat <- as.matrix(raster::extract(x, ludata::getCoordinates(degree=T, order="magpie")))
if (detect_years){
## if names contain any 4 digit num
if (all(grepl("[0-9]{4}",names(x)))) {
years <- as.numeric(gsub(".*([0-9]{4}).*", "\\1", names(x))) # the numbers
names <- gsub("\\.y[0-9]{4}\\D*","",names(x))
if(length(unique(paste0(names, years)))!=length(names(x))) warning("Combination of detected years and names didn't produce enough unique entries. Switch of detect_years.")
colnames(dat) <- paste(names, years, sep=".")
#detected_years <- TRUE
} #else {detected_years <- FALSE}
}
#tmp <- new.magpie(cells_and_regions = paste(geodatadata$region,1:59199,sep="."),years = years,names = names,fill = NA)
tmp <- new.magpie(cells_and_regions = paste(magclass:::magclassdata$half_deg$region,1:59199,sep="."), years = unique(years), names = unique(names), fill = NA)
# geodatadata is part of magclassdata. Should better come from magclass package via a function, so if it is changed there, would be still correct here
tmp[,,] <- dat
attr(tmp, "coordinates") <- ludata::getCoordinates(degree = T)
return(tmp)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.