rgisgeospatialrasterrasterizing

R - Convert points into points in the centre of raster of 30 x 30m


I want to transform a specific dataset of spatial points to points in the centre of a raster. The result sould be spatial points and for each point in the original dataset a point in the centre of the raster.

I made this example code to get a better idea of the task.

library(raster)
library(plyr)
library(ggplot2)
library(viridis)

setwd("C:/Users/chris/Desktop/Regionaler Klimawandel und Gesundheit/Urban COPD/R/Data/")
getwd()

set.seed(55)

r <- raster(xmn= 800000, 
            xmx= 810000,
            ymn= 7200000,
            ymx= 7210000)
p <- as(r@extent, 'SpatialPolygons')
pts <- spsample(p, n = 100, "random")
pts$value <- runif(100, min=0, max=10)
df <- as.data.frame(pts)

ggplot(data= df, aes(x, y, fill =value))+
  geom_point(shape = 21, size = 2)+
  scale_fill_viridis()+
  theme_minimal()

Example points in a Raster

Thank you all!


Solution

  • If I understand you correctly, you want the values column to be associated with the grid points at x, y in the raster object r.

    That being the case, you can append the following line to your above code:

    r <- rasterize(cbind(df$x, df$y), r, df$value, fun = mean)
    

    So now r looks like this:

    r
    #> class      : RasterLayer 
    #> dimensions : 180, 360, 64800  (nrow, ncol, ncell)
    #> resolution : 27.77778, 55.55556  (x, y)
    #> extent     : 8e+05, 810000, 7200000, 7210000  (xmin, xmax, ymin, ymax)
    #> crs        : NA 
    #> source     : memory
    #> names      : layer 
    #> values     : 0.08473639, 9.896253  (min, max)
    
    plot(r)
    

    Note that you have to look closely to see the points because of the resolution of the raster.

    If you lower the resolution of the initial raster, by creating r as:

    r <- raster(xmn= 800000, 
                xmx= 810000,
                ymn= 7200000,
                ymx= 7210000,
                ncols = 50, nrows = 50)
    

    Then you can see the points more clearly and note that they match the points on your ggplot:

    r <- rasterize(cbind(df$x, df$y), r, df$value, fun = mean)
    
    plot(r)
    

    enter image description here

    Created on 2021-11-03 by the reprex package (v2.0.0)