rspatial / terra

R package for spatial data handling https://rspatial.github.io/terra/reference/terra-package.html
GNU General Public License v3.0
543 stars 90 forks source link

`rast(x, type = "xylz")` doesn't work with tibble data frames #1582

Closed Aariq closed 3 months ago

Aariq commented 3 months ago

It appears the layers aren't parsed correctly when the data.frame passed to rast() is a tibble.

library(tibble)
library(terra)
#> terra 1.7.78
set.seed(0)
df <- data.frame(longitude=rep(seq(10,19,1), 3),
                 latitude=rep(seq(10, 19,1), 3),
                 date= as.Date(rep(c("2012-01-01", "2012-02-01", "2012-03-01"), each=10)),
                 vals=rnorm(30,10,5))
x1 <- rast(df, type="xylz")
x1
#> class       : SpatRaster 
#> dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
#> resolution  : 1, 1  (x, y)
#> extent      : 9.5, 19.5, 9.5, 19.5  (xmin, xmax, ymin, ymax)
#> coord. ref. :  
#> source(s)   : memory
#> names       :   vals.1,    vals.2,    vals.3 
#> min values  :  2.30025,  3.812308,  3.577003 
#> max values  : 22.02327, 13.817967, 15.428847 
#> time (days) : 2012-01-01 to 2012-03-01

tbl <- as_tibble(df)
inherits(tbl, "data.frame")
#> [1] TRUE

x2<- rast(tbl, type = "xylz")
x2
#> class       : SpatRaster 
#> dimensions  : 10, 10, 1  (nrow, ncol, nlyr)
#> resolution  : 1, 1  (x, y)
#> extent      : 9.5, 19.5, 9.5, 19.5  (xmin, xmax, ymin, ymax)
#> coord. ref. :  
#> source(s)   : memory
#> name        : c(15340, 15371, 15400) 
#> min value   :                    NaN 
#> max value   :                    NaN

Created on 2024-08-07 with reprex v2.1.0

Aariq commented 3 months ago

One possible simple fix is adding x <- as.data.frame(x) somewhere around here: https://github.com/rspatial/terra/blob/6ebc74539f89bfb3dcfa431be3f34bcd6c0a3646/R/rast.R#L481

rhijmans commented 3 months ago

Thank you, fixed.