Skip to content

Instantly share code, notes, and snippets.

@mxblsdl
Created March 26, 2020 21:27
Show Gist options
  • Save mxblsdl/4b9a2834347a86e57fe9ce20a399aab5 to your computer and use it in GitHub Desktop.
Save mxblsdl/4b9a2834347a86e57fe9ce20a399aab5 to your computer and use it in GitHub Desktop.
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(as.data.frame(x, row.names=row.names, optional=optional, xy=xy, ...))
} else {
tr <- blockSize(x, n=2)
l <- lapply(1:tr$n, function(i)
as.data.table(as.data.frame(getValues(x,
row=tr$row[i],
nrows=tr$nrows[i]),
row.names=row.names, optional=optional, xy=xy, ...)))
v <- rbindlist(l)
}
coln <- names(x)
if(xy) coln <- c("x", "y", coln)
setnames(v, coln)
v
}
if (!isGeneric("as.data.table")) {
setGeneric("as.data.table", function(x, ...)
standardGeneric("as.data.table"))
}
setMethod('as.data.table', signature(x='data.frame'), data.table::as.data.table)
setMethod('as.data.table', signature(x='Raster'), as.data.table.raster)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment