Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Last active May 11, 2022 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h-a-graham/4e0f1017702cc0137442a58f800e426a to your computer and use it in GitHub Desktop.
Save h-a-graham/4e0f1017702cc0137442a58f800e426a to your computer and use it in GitHub Desktop.
A comparison of how to convert a matrix into a spatial raster in either raster, terra or stars format
library(raster)
#> Loading required package: sp
library(stars)
#> Loading required package: abind
#> Loading required package: sf
#> Linking to GEOS 3.10.1, GDAL 3.4.0, PROJ 8.2.0; sf_use_s2() is TRUE
library(terra)
#> terra 1.5.23

v <- volcano[nrow(volcano):1,ncol(volcano):1]

r1 = raster(v, 
            xmn=2667394, xmx=2668004, ymn=6478902, ymx=6479772,
            crs="+proj=nzmg +datum=WGS84")


d <- dim(v)

r2=st_as_stars(sf::st_bbox(c(xmin=2667394, ymin=6478902, 
                             xmax=2668004, ymax=6479772)),
               nx=d[2], ny=d[1], 
               values=t(v), 
               crs="+proj=nzmg +datum=WGS84")



r3 <- rast(vals=v, nrows= d[1], ncols=d[2],
           xmin=2667394, xmax=2668004, ymin=6478902, ymax=6479772,
           crs="+proj=nzmg +datum=WGS84")

plot(r1, col=scico::scico(39), axes=TRUE)

plot(r2, col=scico::scico(39), axes=TRUE)

plot(r3, col=scico::scico(39), axes=TRUE)

Created on 2022-05-11 by the reprex package (v2.0.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment