Convert raster into matrix with R

丶灬走出姿态 提交于 2021-01-27 04:40:46

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/45454334/convert-raster-into-matrix-with-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!