The as.data.frame (xy = true)
function in terra
has been used before for raster data to data frame conversion.
Suddenly I realised that I could use it in conjunction with the data.table
package. I'm not quite able to understand why the (xy =true)
parameter is not explicitly present in the as.data.table
function, how does this process work?
library(terra)
library(data.table)
r <- rast(ncols=10, nrows=10)
values(r) <- 1
s <- c(r, r+1, r+10) |>
`names<-`(c('a', 'b', 'c'))
as.data.table(s, xy = TRUE)
as.data.table
is an S3 generic and the default method is called, which is just a wrapper for as.data.table(as.data.frame(x, ...), ...)
. terra defines an as.data.frame
S3 method for the "SpatRaster" class. The ellipses pass the xy = TRUE
to that method.
Some useful stuff to check all of this:
class(s) #S3
#[1] "SpatRaster"
#attr(,"package")
#[1] "terra"
methods(as.data.table)
data.table:::as.data.table.default
#function (x, ...)
#{
# as.data.table(as.data.frame(x, ...), ...)
#}
#<bytecode: 0x130a72718>
#<environment: namespace:data.table>
terra:::as.data.frame.SpatRaster