在R中为栅格分配值时出错

时间:2017-01-17 14:49:07

标签: r gis raster r-raster

我试图按照代码构建此处描述的残余自动变量模型:https://github.com/jejoenje/PubsRexamples/blob/master/Crase_etal.R#L16

创建大型栅格空间后,在为栅格指定值时会出错。我有1000个随机点来签署光栅,因此有许多点没有数据(NA)。有什么想法吗?

head(xy)
         [,1]    [,2]
[1,] 543510.0 6968620
[2,] 543570.0 6968620
[3,] 543570.0 6968560
[4,] 543599.9 6968560
[5,] 543510.0 6968530
[6,] 543389.9 6968470


head(xy_residuals)
      [,1]    [,2]       [,3]
1 543510.0 6968620 -0.4257671
2 543570.0 6968620 -0.4541684
3 543570.0 6968560 -0.4310492
4 543599.9 6968560 -0.4649595
5 543510.0 6968530 -0.5506348
6 543389.9 6968470 -0.4928708

summary(xy)
           X               Y   
Min.   :538800   Min.   :6931480  
1st Qu.:540480   1st Qu.:6932860  
Median :541350   Median :6935320  
Mean   :541529   Mean   :6943218  
3rd Qu.:542670   3rd Qu.:6954003  
Max.   :544290   Max.   :6968620  

# Define raster ymn, ymx, xmn and xmx from coordinates 
# ncol=xmx-xmn nrow=ymx-ymn.

rast <- raster(ncol = 5490, nrow = 37140, ymn = 6931480, ymx = 6968620, 
               xmn = 538800, xmx = 544290)
rast

class       : RasterLayer 
dimensions  : 37140, 5490, 203898600  (nrow, ncol, ncell)
resolution  : 1, 1  (x, y)
extent      : 538800, 544290, 6931480, 6968620  (xmin, xmax, ymin, ymax)
coord. ref. : NA 

有问题的电话:

rast[cellFromXY(rast, xy)] <- xy_residuals[, 3]
  

.replace(x,i = i,value = value,recycle = 1)出错:       如果长度不是1或要替换的单元格数**,则不能替换大型栅格对象中的值**

1 个答案:

答案 0 :(得分:2)

错误消息说明为什么会发生这种情况(但也许这个“功能”需要一些改进。)光栅非常大,可能不适合内存(RAM)。评估可能过于保守。您可以通过rasterOptions进行调整,也可以尝试:

library(raster)
r <- raster(ncol = 10, nrow = 10, ymn = 6931480, ymx = 6968620, xmn = 538800, xmx = 544290)
m <- matrix(c(539868,542002,542409,6945031,6940012,6935997, 1, 2, 3), 3, 3)    
cells <- cellFromXY(r, m[,1:2])

# create a large vector with all cells
v <- rep(NA, ncell(r))
v[cells] <- m[,3]
v <- setValues(r, v)

如果这不起作用,你可以查看update,但这会因为覆盖文件中的数据而风险更大,但在这种情况下这不应该是一个问题。

r <- setValues(r, NA)
# that probably creates a file on disk. If not do
# r <- writeRaster(r, filename='test.grd')

r <- update(r, cell=cells, v=m[,3])