使用SF聚合栅格中的值 [英] Aggregate values in raster using SF
本文介绍了使用SF聚合栅格中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用SF聚合栅格中的值
我需要的是为每个栅格聚合一些度量值。 假设我们有一些数据坐标和值,并且我想创建一个热图。
首先,我使用Simple Feature框架创建了一个网格和栅格。 现在我需要获取df
中的每个坐标,并检查它们是否在一个栅格中。然后为每个栅格计算任何其他聚合函数的平均值。
# Packages ----------------------------------------------------------------
library(raster)
library(tidyverse)
library(sf)
library(sp)
# Border Data and Grid ----------------------------------------------------
Regions <- getData("GADM", country= "CZE", level = 1)
Regions %>%
Regions <-
Regions %>% st_as_sf()
grid_spacing <- 0.25
polygony <- st_make_grid(Regions, square = T,
cellsize = c(grid_spacing, grid_spacing)) %>%
st_sf()
plot(polygony, col = 'white')
plot(st_geometry(CZ), add = T)
A = st_intersection(polygony, CZ)
# Artifial Values to be use -----------------------------------------------
df <-
tibble(long = runif(500, 13.27857, 14),
lat = runif(500, 49, 50),
price = rnbinom(500, size = 40, 0.3))
df %>%
ggplot(aes(long, lat, color = values)) +
geom_point()
A <-
A %>%
# Here Val shall be calculated as a mean of observations within each rastel grid cell
mutate(val = rnorm(n = 202))
# Since not every raster cell has observations inside some NAN will be present
A[5, 'val'] = NaN
A[25, 'val'] = NaN
A %>%
ggplot(aes(fill = val)) +
geom_sf()
# What I need -------------------------------------------------------------
# For each raster in A calculate the mean of price for coordinates within this raster grid.
我基本上需要SF框架中的一些等价物https://www.rdocumentation.org/packages/raster/versions/3.4-5/topics/rasterize。
但是,我希望绘图看起来像示例中我确实需要栅格具有给定网格的形状。
推荐答案
要聚合网格上的点值并保留SF,您可以执行以下操作:
library(dplyr)
library(sf)
# get data. using your example, we'll take spatial data from the raster package
Regions <- raster::getData("GADM", country= "CZE", level = 1)
# convert spdf to sf
Regions <- Regions %>% st_as_sf()
# create a grid sf object
grid_spacing <- 0.25
polygony <- st_make_grid(Regions, square = T,
cellsize = c(grid_spacing, grid_spacing)) %>%
st_sf() %>%
mutate(ID = row_number()) # add a unique ID to each grid cell
# clip grid to shape of country polygons
A <- st_intersect(polygony, Regions)
# create fake data with coordinates and prices
df <- tibble(long = runif(500, 13.27857, 14),
lat = runif(500, 49, 50),
price = rnbinom(500, size = 40, 0.3))
# convert the df to sf point layer
points <- st_as_sf(df, coords = c("long", "lat"), crs = st_crs(A))
# spatially join grid to points, so that each point is assigned the grid ID into which it falls
pointsID <- st_join(points, A)
# group and summarize point values by grid ID
pointsID <- pointsID %>%
as.data.frame() %>%
group_by(ID) %>%
summarize(avg_price = mean(price))
# join aggregated values back to your grid
A<- left_join(A, pointsID, by = "ID")
plot(A["avg_price"])
这篇关于使用SF聚合栅格中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文