如何从相应多边形的栅格中提取值?
How to extract values from a raster for corresponding polygon?
我有一个栅格和一个 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
我想将栅格与 shapefile 相交以生成具有两列的 data.frame
:
name (the names in column name in sf) value (corresponding value in r)
请使用 exactextractr
库找到以下一种可能的解决方案。
Reprex
- 代码
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]
- 输出
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
由 reprex package (v2.0.1)
于 2022-02-28 创建
我有一个栅格和一个 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
我想将栅格与 shapefile 相交以生成具有两列的 data.frame
:
name (the names in column name in sf) value (corresponding value in r)
请使用 exactextractr
库找到以下一种可能的解决方案。
Reprex
- 代码
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]
- 输出
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
由 reprex package (v2.0.1)
于 2022-02-28 创建