使用 R 将栅格转换为矩阵 [英] Convert raster into matrix with R

查看:117
本文介绍了使用 R 将栅格转换为矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将原始矩阵转换为栅格以使用焦点函数,然后我想将栅格转换回矩阵.但是当我尝试使用光栅函数 as.matrix() 时出现错误消息.即使是这个非常简单的例子:

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)

这是我得到的:

数组错误(x, c(length(x), 1L), if (!is.null(names(x))) list(names(x), :

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

'dimnames' [1] 的长度不等于数组范围

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

我正在使用 RSTUDIO、R 版本 3.4.0 和 ncdf4rasterrgdal 库.

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

感谢您的帮助.

推荐答案

确保您使用的是 raster 包中的 as.matrix 函数,而不是基础版本.

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

我假设你用 libraryrequire 加载了包:

I assume you loaded the package with library or require:

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

当我使用 as.matrix 时,它可以工作:

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 ...

当您使用 as.matrix 的基本版本时,您将收到以下错误消息:

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

因此,如果仅加载库对您不起作用,请尝试像这样调用函数:raster::as.matrix(r)

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

这篇关于使用 R 将栅格转换为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆