Search code examples
rrastertiff

How to extract information based on shapefile from dataframe?


I have a dataframe

lon lat year        U       CP     PS     FR     NT
1:  87  46 1650     0        0   0.198      0   0.802
2:  87  46 1651     0        0   0.197      0   0.803
3:  87  46 1652     0        0   0.195      0   0.805
4:  87  46 1653     0        0   0.193      0   0.807
5:  87  46 1654     0        0   0.192      0   0.808
6:  87  46 1655     0        0   0.190      0   0.810

I have dataframe that covers lon and lat globally. I would like to extract information according to my shape file. I donot know how can I make a reproducible example of raster showing global data. But I have made snippet show longitude and latitude.


Solution

  • Here is how you can make a global raster

    library(raster)
    r <- raster()
    values(r) <- 1:ncell(r)
    

    You can then extract values for point locations like this

    lonlat <- cbind(c(87, 86), c(46, 47))
    extract(r, lonlat)
    [1] 16108 15747