Search code examples
rmatrixrasterr-raster

Extracting some values from raster as a matrix, doing a transformation and putting the transformed values to their original place


Let's say I have a raster image x:

library(raster)
x = raster(ncol=10, nrow=10, vals = c(rep(NA, 10), rnorm(80), rep(NA, 10)))

Now I convert the rows and columns that are not NAs into a matrix

x_mat = raster::as.matrix(x)
x_mat_complete = x_mat[complete.cases(x_mat),]

Here I do some modification to the matrix x_mat_complete:

x_mat_complete_modified = x_mat_complete + 1

Now, what I want is to put x_mat_complete_modified back to its place in the original raster image x in such a way that the NA pixels remain the same. I can't figure out how to do this.

In other words, I want to replace x_mat_complete with x_mat_complete_modified in the raster image x keeping all the NAs unmodified.


Solution

  • What you want to do seems a bit iffy --- there are likely better ways that avoid creating a matrix, but here is a solution.

    Example data with a minor change to better illustrate what complete cases does (remove all rows that have at least one NA)

    library(raster)
    set.seed(1)
    x = raster(ncols=10, nrows=10, vals = c(rep(NA, 8), rnorm(84), rep(NA, 8)))   
    x_mat = raster::as.matrix(x)
    

    Solution

    i = complete.cases(x_mat)
    cc = x_mat[i,]
    x[which(i),] = cc + 10
    

    With your example data you could just do

    set.seed(1)
    x = raster(ncols=10, nrows=10, vals = c(rep(NA, 10), rnorm(80), rep(NA, 10)))   
    y <- x + 10
    

    See trim to remove outer rows and columns with NA values.