canderson156
canderson156

Reputation: 1281

How can I create a reproducible example of a SpatRaster (terra)?

For a question that is specific to my particular dataset, how can I make a reproducible example of that dataset if I have it stored as a SpatRaster in R?

The data structure is complex enough that I don't know how to freehand invent a simpler version and read it as a SpatRast (i.e. x <- rast(????????)

I also haven't been able to figure out how I could use a package or command to extract enough information to provide what is functionally a reproducible example either

See my previous question for an example: How can I add a class name to numeric raster values in a terra SpatRaster?

Upvotes: 4

Views: 379

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47536

You can create objects from scratch like this:

library(terra)
r <- rast()
s <- rast(ncols=22, nrows=25, nlyrs=5, xmin=0)

See ?terra::rast for additional arguments you can use and for alternative approaches.

You can also use a file that ships with R. For example:

f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)

You can also create from scratch a new SpatRaster with (mostly) the same properties with what is returned by

as.character(r) 

And then recreate it with something like

r <- rast(ncols=95, nrows=90, nlyrs=1, xmin=5.74166666666667, xmax=6.53333333333333, ymin=49.4416666666667, ymax=50.1916666666667, names=c('elevation'), crs='GEOGCRS[\"WGS 84\",DATUM[\"World Geodetic System 1984\",ELLIPSOID[\"WGS 84\",6378137,298.257223563,LENGTHUNIT[\"metre\",1]]],PRIMEM[\"Greenwich\",0,ANGLEUNIT[\"degree\",0.0174532925199433]],CS[ellipsoidal,2],AXIS[\"geodetic latitude (Lat)\",north,ORDER[1],ANGLEUNIT[\"degree\",0.0174532925199433]],AXIS[\"geodetic longitude (Lon)\",east,ORDER[2],ANGLEUNIT[\"degree\",0.0174532925199433]],ID[\"EPSG\",4326]]')
r <- init(r, "cell")

If you cannot replicate your error with example data, this may give you a hint about the problem. Does it have to do with NAs? The file being on disk? The file format? One tricky situation is where there is a difference if the real file is much larger. You can simulate a large file by setting terraOptions(todisk=TRUE) and using a steps argument in a function, e.g.

b <- clamp(x, steps=5) 

If none of that allows you to replicate an error, your last resort is to provide a link to the file so that others can download it. If you cannot do that, then at least show the content of the SpatRaster x with show(x) and provide the code to create a similar object with as.character(x)

Upvotes: 4

Related Questions