How to replace NA's in a raster object

前端 未结 2 519
梦毁少年i
梦毁少年i 2021-02-05 14:53

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

library(raster)
filename <- system.file(\"external/test         


        
相关标签:
2条回答
  • 2021-02-05 15:19

    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)
    

    enter image description here


    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
    
    0 讨论(0)
  • 2021-02-05 15:21

    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))
    
    0 讨论(0)
提交回复
热议问题