tlhenvironment
tlhenvironment

Reputation: 349

Read out values in matrix form r-terra

I have a SpatRaster file created by rast() from the terra package, and I want to read out the values of the raster in matrix form. If the underlying raster is has 10 rows and 10 columns, I want the values to be in the same format, but as a matrix.

I tried some ways, e.g.:

matrix(1:100, nrow = 10, ncol = 10) -> mm
rast(mm) -> spat_raster

as.matrix(spat_raster) %>% dim

However, the output is a 100x1 matrix, and not a 10x10. Also

values(spat_raster, mat = T)

doesn't work. Any ideas?

Upvotes: 1

Views: 1493

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47036

You can use as.matrix with argument wide=TRUE. The below is from the example in ?as.matrix

library(terra)
r <- rast(ncol=2, nrow=2)
values(r) <- 1:ncell(r)
as.matrix(r, wide=TRUE)
#     [,1] [,2]
#[1,]    1    2
#[2,]    3    4

You could also do (with a one-layer SpatRaster)

d <- dim(r)
matrix(values(r), d[1], d[2], byrow=TRUE)

Upvotes: 6

Related Questions