Search code examples
rr-rasterr-sp

R: change raster values where spatial points overlay


Consider the following data:

library(sp)  
library(raster)

# create raster
r <- matrix(c(1.8, 1.2, 1.8, 1.2, 2.5, 2.7, 8.5, 7, 2), 3,3)

r <- raster(r)
extent(r) <- c(45,46,54,55)
projection(r) <- "+proj=utm +zone=33 +ellps=GRS80 +units=m +no_defs"

# create points
coords <- data.frame(x = c(45.6, 45.2),
                     y = c(54.8, 54.2))

data <- data.frame(a = c(20,22), b = c(1.5, 2.5))
p <- SpatialPointsDataFrame(coords = coords,
                           data = data, 
                           proj4string = crs(r))

plot(r)
plot(p, add=TRUE)

I have 2 points which are covering 2 raster cells. I want to replace these raster cell values by the values of a of the SpatialPointsDataFrame p. Therefore I transformed the SpatialPointsDataFrame into a raster:

p_ras <- rasterize(x = p, y = r, field = "a")

How can I update the values of r using those of p_ras, where p_ras has non-empty cell values and assign the values by location to r?


Solution

  • Your example data

    library(raster)
    r <- raster(ncol=3, nrow=3, ext=extent(c(45,46,54,55)), crs = "+proj=utm +zone=33 +ellps=GRS80 +units=m")
    values(r) <- c(1.8, 1.2, 1.8, 1.2, 2.5, 2.7, 8.5, 7, 2)
    coords <- data.frame(x = c(45.6, 45.2), y = c(54.8, 54.2))
    data <- data.frame(a = c(20,22), b = c(1.5, 2.5))
    p <- SpatialPointsDataFrame(coords = coords, data = data, proj4string = crs(r))
    

    You were on the right track with rasterize. Just add argument update=TRUE

    x <- rasterize(p, r, field="a", update=TRUE)
    

    That is equivalent to

    p_ras <- rasterize(p, r, field = "a")
    p_ras <- cover(p_ras, r)
    

    And that should be clearer and more efficient than overlay. The approach with xyFromCell is risky for large objects as it may force all values into memory.