Search code examples
rrasterterra

replace values in raster for selected cells


I have a big raster which has value of 1 in each cell

r <- terra::rast(ncols=129600, 
             nrows=64800, 
             xmin=-180, 
             xmax=180, 
             ymin=-90, 
             ymax=90,
             resolution = 0.002777778,
             crs="+proj=longlat +datum=WGS84",
             vals = 1)

I have a csv file that contains lon, lat and value

dat <- structure(list(lat = c(81.3152777777778, 81.3125, 81.3097222222222, 81.3069444444444, 81.2597222222222, 
                           81.2569444444445, 81.2541666666667, 81.2513888888889, 81.2486111111111, 81.2458333333333), 
                     lon = c(-19.9986111111111, -19.9986111111111, -19.9986111111111, -19.9986111111111, -19.9986111111111, 
                             -19.9986111111111, -19.9986111111111, -19.9986111111111, -19.9986111111111, -19.9986111111111), 
                     value = c(0.432098765432099, 0.432098765432099, 0.432098765432099, 0.432098765432099, 0.493827160493827, 
                               0.506172839506173, 0.45679012345679, 0.407407407407407, 0.358024691358025, 0.308641975308642)), 
                     row.names = c(NA, -10L), class = c("data.table", "data.frame"))

One thing to note is that dat is just a snapshot of the actual data I have and is actually is an irregular grid.

What I want to do is to fill the raster r with the value in dat using the lat/lon in dat. To elaborate on this, for every lat/lon in dat, use its corresponding value to fill in the value in r. So when I tried to convert dat into a raster so that I can do For those lat/lon that are not present in dat but are present in r, leave the default value to 1.


Solution

  • You can make use of terra::rasterize() with background = 1 to get your desired raster, as far as I understand:

    # data.table to data.frame
    dat <- as.data.frame(dat)
    
    # create vector
    v <- terra::vect(dat, geom = c("lat", "lon"), crs = "+proj=longlat +datum=WGS84")
    
    # burn values from points to raster
    terra::rasterize(x = v, y = r, field = "value", background = 1) 
    #> class       : SpatRaster 
    #> dimensions  : 180, 360, 1  (nrow, ncol, nlyr)
    #> resolution  : 0.002777778, 0.002777778  (x, y)
    #> extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #> coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
    #> source      : memory 
    #> name        :    lyr.1 
    #> min value   : 0.308642 
    #> max value   :        1
    

    You would not need to specify vals = 1 in r <- rast() here since the grid is only used for geometry purposes.