Convert raster into matrix with R

Christophe Lavaysse picture Christophe Lavaysse · Aug 2, 2017 · Viewed 7.2k times · Source

I'm currently convert original matrix into a raster to use the focal function, then I would like to convert back the raster into matrix. But I have an error message when I try to use the raster function as.matrix(). Even with this very simple example:

r <- raster(ncol=3, nrow=3)
r[] <- 1:ncell(r)
as.matrix(r)

Here is what I got:

Error in array(x, c(length(x), 1L), if (!is.null(names(x))) list(names(x), :

length of 'dimnames' [1] not equal to array extent

I'm using RSTUDIO, R version 3.4.0 and ncdf4, raster and rgdal librairies.

Thank you for your help.

Answer

Val picture Val · Aug 3, 2017

Make sure that you're using the as.matrix function from the raster package, not the base version.

I assume you loaded the package with library or require:

library(raster)
r <- raster()
r[] <- 1:ncell(r)

When I use as.matrix, it works:

> str(as.matrix(r))
 int [1:180, 1:360] 1 361 721 1081 1441 1801 2161 2521 2881 3241 ...

When you use the base version of as.matrix, you'll get exactly this error message:

> base::as.matrix(r)
Error in array(x, c(length(x), 1L), if (!is.null(names(x))) list(names(x),  : 
  length of 'dimnames' [1] not equal to array extent

So if only loading the library doesn't work for you, try calling the function like this: raster::as.matrix(r)