Search code examples
rrasterr-raster

How to build a raster/raster stack to accept values based on df


I am trying to build some data structures to accept data.

r1 = raster(matrix(NA,3,3)) 
df <- data.frame(a = c(1,2,3), b = c(2,2,2), val = c(10,20,30)) #example of data

Then I was hoping to fill this raster with values based on a df. But not like this, but based on the values of df$a and df$b.

plot(r1) #empty
values(r1) <- c(NA, df$val[[1]], NA, NA,df$val[[2]],NA,NA,NA,df$val[[3]]) #unindex filling
plot(r1) #wanted result

I hope its clear what I am hoping to achieve. Its geolocation data, and therefore df$a and df$b will become Lon and Lat, and df$val will be an environmental variable. The layers will become monthly averages. Not all raster cells will have variables.

Thanks.


Solution

  • Given a raster and coordinates, you can compute the cell numbers and use these to assign the values. Something like this

    library(raster)
    r <- raster(nrows=5, ncols=5, xmn=0, xmx=5, ymn=0, ymx=5) 
    df <- data.frame(x = c(1,2,3), y = c(2,2,2), val = c(10,20,30))
    
    cells <- cellFromXY(r, df[,1:2])
    r[cells] <- df$val
    

    Also see ?rasterFromXYZ