How to replace NA's in a raster object

岁酱吖の 提交于 2020-01-12 03:21:50

问题


I need to replace the NA's in the raster object (r) from the example below.

library(raster)
filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)

I also tried to remove these these (and place the result in a data.frame), but to no avail.

dfr <- as.data.frame(r, na.rm=T)
summary(dfr)
# test       
# Min.   : 128.4  
# 1st Qu.: 293.2  
# Median : 371.4  
# Mean   : 423.2  
# 3rd Qu.: 499.8  
# Max.   :1805.8  
# NA's   :6097

回答1:


I'm not sure it makes sense to remove NA values from a raster object, but you can easily replace it.

For example:

oldpar <- par(mfrow=c(1, 2))
plot(r)
r[is.na(r)] <- 250
plot(r)
par(oldpar)


If you really want to, you can extract the raster values into a vector and then remove the NA values. (Although, since you lose the spatial information, I can't see how this can be helpful.)

r <- raster(filename)

r <- values(r)
head(r)
[1] NA NA NA NA NA NA

head(na.omit(r))
[1] 633.686 712.545 654.162 604.442 857.256 755.506



回答2:


A more memory safe approach (for large files) would be to use reclassify:

library(raster)
filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)
rna <- reclassify(r, cbind(NA, 250))


来源:https://stackoverflow.com/questions/11966503/how-to-replace-nas-in-a-raster-object

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