Tpellirn
Tpellirn

Reputation: 796

How to extract values from a raster for corresponding polygon?

I have a raster and a shapefile:

r <- raster(matrix(rnorm(10*12), nrow=10), xmn = -180, xmx= 180, ymn = -90, ymx= 90)
myurl <- "http://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_050_00_500k.json"
geo <- readLines(myurl)
geo <- paste0(geo, collapse = "")
library(geojsonsf)
system.time({ sf <- geojson_sf(geo)})
library(sf) 
sf

I would like to intersect the raster with the shapefile to produce a data.frame with two columns:

name (the names in column name in sf)      value (corresponding value in r)

Upvotes: 1

Views: 496

Answers (1)

lovalery
lovalery

Reputation: 4652

Please find below one possible solution using the exactextractr library.

Reprex

  • Code
library(raster)
library(geojsonsf)
library(sf)

library(exactextractr)


# add crs information for the raster 'r'
crs(r) <- 4326

# extract the 'r' raster value for each polygon 'NAME' in 'sf'
res <- do.call(rbind, exactextractr::exact_extract(r, sf, include_cols = 'NAME'))[-3]
  • Output
head(res)
#>        NAME     value
#> 1  Cleburne 0.5184757
#> 2    Coffee 0.5184757
#> 3     Coosa 0.5184757
#> 4 Covington 0.5184757
#> 5  Crenshaw 0.5184757
#> 6      Dale 0.5184757

Created on 2022-02-28 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions