Search code examples
rgeospatialpolygonspatialr-raster

Merging a large spatial polygon that looks like a grid with a raster layer R


I have a large Spatial polygon data frame, i also have a raster layer that has many points of information. Both are geo referenced and i would like to overlay the grid on top of my raster layer and assign each point inside to a grid cell that it falls into. The problem i am running into is that the grid i have is not being treated like a grid but just a plotted polygon.This is what i get when i plot one on top of the other in ggplot after converting both to points.s

A look at the data changed into points:

Grid:

      long    lat order  hole piece   id  group 
1 -101.940 31.710     1 FALSE     1 1012 1012.1  
2 -101.940 31.715     4 FALSE     1 1012 1012.1  
3 -101.940 31.710     5 FALSE     1 1012 1012.1  
4 -101.930 31.670     3 FALSE     1 1016 1016.1  
5 -101.925 31.670     4 FALSE     1 1016 1016.1  
6 -101.890 31.715     1 FALSE     1 1028 1028.1  

Raster Layer:

      longS     latS intensity
1 -101.9395 31.73822        85
2 -101.9394 31.73822        85
3 -101.9393 31.73822        86
4 -101.9392 31.73822        87
5 -101.9391 31.73822        62
6 -101.9390 31.73822        65

Transformations done using:

S <- rasterToPoints(S)
SHP <- fortify(SHP)

Things i have tried: Different merging techniques for polygons and raster but for the examples i found people made there own grid and in this case i must use this grid or one with the exact dimensions.

Iv also tried to change them to points and merge based on the id of the polygon but i found that the id is not related to the cell units just the lines being made themselves.

Any help on merging the two and assigning the points inside the shown grid cells would be much appreciated.


Solution

  • Here is some simple example data:

    library(raster)
    r <- raster(nrow=2, ncol=4, vals=1:8)  
    p <- as(r, 'SpatialPolygonsDataFrame')
    r <- disaggregate(r, 2)
    values(r) <- 1:ncell(r)
    plot(r)
    plot(p, add=TRUE)
    

    With SpatialPolygonsDataFrame p and RasterLayer r, you can now do

    p$ID <- 1:length(p)
    x <- rasterize(p, r, 'ID')
    s <- stack(x, r)
    head(values(s))
    
    #     layer.1 layer.2
    #[1,]       1       1
    #[2,]       1       2
    #[3,]       2       3
    #[4,]       2       4
    #[5,]       3       5
    #[6,]       3       6
    

    Or

    e <- extract(r, p)
    
    e[1:3]
    #[[1]]
    #[1]  1  2  9 10
    #[[2]]
    #[1]  3  4 11 12
    #[[3]]
    #[1]  5  6 13 14