Last active
July 26, 2019 07:51
-
-
Save Martin-Jung/403b6293275d0493e8259913aec9d45b to your computer and use it in GitHub Desktop.
Function to convert a raster to a data.table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
as.data.table.raster <- function(x, row.names = NULL, optional = FALSE, | |
xy = FALSE, inmem = canProcessInMemory(x, 2), | |
...) { | |
stopifnot(require("data.table")) | |
if(inmem) { | |
v <- as.data.table(raster::as.data.frame(x, row.names=row.names, | |
optional=optional, xy=xy, ...)) | |
coln <- names(x) | |
if(xy) coln <- c("x", "y", coln) | |
setnames(v, coln) | |
} else { | |
tr <- blockSize(x) | |
l <- lapply(1:tr$n, function(i) { | |
DT <- as.data.table(as.data.frame(getValues(x, row = tr$row[i], | |
nrows = tr$nrows[i]), ...)) | |
if(xy == TRUE) { | |
cells <- cellFromRowCol(x, c(tr$row[i], tr$row[i] + tr$nrows[i] - 1), | |
c(1, ncol(br))) | |
coords <- xyFromCell(x, cell = cells[1]:cells[2]) | |
DT[, c("x", "y") := data.frame(xyFromCell(x, cell = cells[1]:cells[2]))] | |
} | |
DT | |
}) | |
v <- rbindlist(l) | |
coln <- names(br) | |
if(xy) { | |
coln <- c("x", "y", coln) | |
setcolorder(v, coln) | |
} | |
} | |
v | |
} | |
dt_to_raster <- function(dt, CRSobj, filename = NULL) { | |
if(any(!c("x", "y") %in% colnames(dt))) { | |
stop("dt needs planar coordinates in x, y format") | |
} | |
coordinates(dt) = ~x+y | |
proj4string(dt) <- CRSobj | |
gridded(dt) = TRUE | |
if(ncol(dt) > 1) { | |
dtr <- brick(dt) | |
} else { | |
dtr <- brick(dt) | |
} | |
if(!is.null(filename)) dtr <- writeRaster(dtr, filename) | |
return(dtr) | |
} | |
dt_list_to_raster <- function(base, inlist, CRSobj) { | |
dts <- lapply(inlist, function(x) { | |
dt <- cbind(base, x) | |
dtr <- dt_to_raster(dt, CRSobj = CRSobj) | |
}) | |
if(!is.null(names(inlist))) names(dts) <- names(inlist) | |
return(dts) | |
} | |
raster_list_to_dt <- function(inlist, base = TRUE) { | |
if(base == TRUE) { | |
base_dt <- as.data.table.raster(inlist[[1]], xy = TRUE)[, c("x", "y"), | |
with = FALSE] | |
base_dt[, ind := 1:nrow(base_dt)] | |
} | |
dts <- lapply(inlist, function(x) { | |
dt <- as.data.table.raster(x) | |
}) | |
if(!is.null(names(inlist))) names(dts) <- names(inlist) | |
if(base == TRUE) outlist <- list(base_dt, dts) | |
if(base == FALSE) outlist <- dts | |
return(outlist) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment