空间连接与空间操作
应用 st_join()、st_intersection()、st_buffer() 和 st_distance()
空间连接与空间操作 是 CoddyKit 上的免费 R Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 R Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 R Academy 课程共包含 4 节课。
使用 st_join 进行空间连接
st_join(x, y) 会执行空间左连接:对于 x 中的每个要素,它会查找 y 中满足空间谓词(默认值:st_intersects)的要素,并附加这些要素的属性。多个匹配项会产生多行。
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
# Create random points within NC bounding box
set.seed(42)
bbox <- st_bbox(nc)
pts <- data.frame(
lon = runif(20, bbox['xmin'], bbox['xmax']),
lat = runif(20, bbox['ymin'], bbox['ymax'])
)
pts_sf <- st_as_sf(pts, coords = c('lon', 'lat'), crs = 4326)
# Spatial join: assign county attributes to each point
pts_with_county <- st_join(pts_sf, nc['NAME'])
cat('Points with county:\n')
print(head(pts_with_county[, c('NAME', 'geometry')], 5))st_within:点在多边形内
st_within(x, y) 会返回一个稀疏逻辑矩阵,用于指示 x 中的每个要素是否完全位于 y 中的某个要素内。它比 st_intersects 更严格——仅接触边界不算在内。
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
# Random points
set.seed(7)
bbox <- st_bbox(nc)
pts_sf <- st_as_sf(
data.frame(
lon = runif(30, bbox['xmin'], bbox['xmax']),
lat = runif(30, bbox['ymin'], bbox['ymax'])
),
coords = c('lon', 'lat'), crs = 4326
)
# Which points are within NC at all?
within_nc <- st_within(pts_sf, st_union(nc), sparse = FALSE)[, 1]
cat('Points within NC:', sum(within_nc), '/ 30\n')
# Keep only points inside NC
pts_inside <- pts_sf[within_nc, ]
cat('Kept:', nrow(pts_inside), 'points\n')st_intersects:重叠检查
当要素共享任何几何部分(边界或内部)时,st_intersects(x, y) 会返回 TRUE。它是限制最宽松的拓扑谓词。传入 sparse = FALSE,可以获得逻辑矩阵,而不是索引向量列表。
library(sf)
# Create two overlapping polygons
poly1 <- st_polygon(list(matrix(c(0,0, 2,0, 2,2, 0,2, 0,0), ncol=2, byrow=TRUE)))
poly2 <- st_polygon(list(matrix(c(1,1, 3,1, 3,3, 1,3, 1,1), ncol=2, byrow=TRUE)))
poly3 <- st_polygon(list(matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol=2, byrow=TRUE)))
sfc <- st_sfc(poly1, poly2, poly3, crs = 32119)
# Intersects matrix
mat <- st_intersects(sfc, sparse = FALSE)
cat('Intersects matrix:\n')
print(mat)
cat('\npoly1 intersects poly2:', mat[1, 2], '\n')
cat('poly1 intersects poly3:', mat[1, 3], '\n')st_buffer:创建缓冲区
st_buffer(sf_obj, dist) 会以指定距离围绕每个要素创建缓冲区多边形。在地理 CRS 中,距离单位是度;在投影 CRS 中,距离单位是米——为了获得准确结果,请始终先进行投影,再创建缓冲区。
library(sf)
# City points in WGS84
cities <- data.frame(
city = c('Raleigh', 'Charlotte', 'Greensboro'),
lon = c(-78.639, -80.843, -79.792),
lat = c(35.779, 35.227, 36.073)
)
cities_sf <- st_as_sf(cities, coords = c('lon', 'lat'), crs = 4326)
# Project to metres for accurate buffering (NC State Plane)
cities_proj <- st_transform(cities_sf, 32119)
# 25 km buffer around each city
buffers <- st_buffer(cities_proj, dist = 25000)
cat('Buffer geometry type:', unique(as.character(st_geometry_type(buffers))), '\n')
cat('Buffer area (km2):', round(as.numeric(st_area(buffers[1, ])) / 1e6, 2), '\n')
cat('Expected (pi*25^2):', round(pi * 25^2, 2), 'km2\n')st_area:多边形面积
st_area(sf_obj) 会计算每个多边形的面积。在地理 CRS 中,它返回以球面度量单位表示的值(没有实用意义);在使用米制单位的投影 CRS 中,它返回平方米。结果会携带 units 软件包提供的单位信息。
library(sf)
library(units)
nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))
nc_proj <- st_transform(nc, 32119) # NC State Plane, metres
# Area in m2 with units
nc_proj$area_m2 <- st_area(nc_proj)
# Convert to km2
nc_proj$area_km2 <- set_units(nc_proj$area_m2, 'km^2')
# Summary statistics
cat('Smallest county:', nc_proj$NAME[which.min(nc_proj$area_km2)],
round(min(as.numeric(nc_proj$area_km2)), 1), 'km2\n')
cat('Largest county: ', nc_proj$NAME[which.max(nc_proj$area_km2)],
round(max(as.numeric(nc_proj$area_km2)), 1), 'km2\n')st_distance:成对距离
st_distance(x, y) 会计算 x 中所有要素与 y 中所有要素之间的距离矩阵。在 WGS84 上,它使用大地测量距离;在投影 CRS 上,它使用欧几里得距离。结果会携带 units 元数据。
library(sf)
cities <- data.frame(
city = c('Raleigh', 'Charlotte', 'Greensboro', 'Wilmington'),
lon = c(-78.639, -80.843, -79.792, -77.909),
lat = c(35.779, 35.227, 36.073, 34.226)
)
cities_sf <- st_as_sf(cities, coords = c('lon', 'lat'), crs = 4326)
# Geodesic distance matrix (metres)
dist_m <- st_distance(cities_sf)
dist_km <- round(dist_m / 1000)
rownames(dist_km) <- cities$city
colnames(dist_km) <- cities$city
cat('Distance matrix (km):\n')
print(dist_km)
# Nearest neighbour for Raleigh
raleigh_dist <- as.numeric(dist_km['Raleigh', -1])
cat('\nNearest to Raleigh:',
cities$city[-1][which.min(raleigh_dist)],
min(raleigh_dist), 'km\n')st_union:融合几何对象
st_union(sf_obj) 会将所有要素合并为一个几何对象,并消除内部边界。它适合用于根据多个县多边形创建单一轮廓多边形,或合并一组缓冲区。
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 32119
)
# Dissolve all counties into the NC state outline
nc_state <- st_union(nc)
cat('Counties before union:', nrow(nc), '\n')
cat('Features after union:', length(nc_state), '(single geometry)\n')
cat('Geometry type:', as.character(st_geometry_type(nc_state)), '\n')
# Area check: sum of counties == state area
county_area_sum <- sum(as.numeric(st_area(nc)))
state_area <- as.numeric(st_area(nc_state))
cat('Sum of county areas:', round(county_area_sum / 1e9, 2), 'km2\n')
cat('State area: ', round(state_area / 1e9, 2), 'km2\n')st_intersection:裁剪
st_intersection(x, y) 会返回每对要素的几何交集,即两个几何对象共同覆盖的区域。它用于将一个图层裁剪到另一个图层的范围内。
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
# Clip NC counties to a bounding rectangle (eastern NC)
clip_box <- st_as_sfc(st_bbox(c(
xmin = -78, xmax = -75,
ymin = 33.5, ymax = 36.5
), crs = 4326))
eastern_nc <- st_intersection(nc, clip_box)
cat('Original features:', nrow(nc), '\n')
cat('Clipped features: ', nrow(eastern_nc), '\n')
cat('Geometry types: ', paste(unique(as.character(st_geometry_type(eastern_nc))), collapse = ', '), '\n')使用 dplyr 进行空间聚合
将 st_join() 与 dplyr::group_by() 和 summarise() 结合使用,可以按多边形聚合点数据。对 sf 对象进行分组时,几何列也会自动聚合(默认进行合并)。
library(sf)
library(dplyr)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)
# Generate random sales events in NC
set.seed(99)
bbox <- st_bbox(nc)
pts <- st_as_sf(
data.frame(
lon = runif(200, bbox['xmin'], bbox['xmax']),
lat = runif(200, bbox['ymin'], bbox['ymax']),
sales = runif(200, 100, 1000)
),
coords = c('lon', 'lat'), crs = 4326
)
# Join then aggregate
result <- st_join(pts, nc['NAME']) |>
filter(!is.na(NAME)) |>
st_drop_geometry() |>
group_by(NAME) |>
summarise(total_sales = sum(sales), n_events = n()) |>
arrange(desc(total_sales))
cat('Top 5 counties by sales:\n')
print(head(result, 5))st_nearest_feature
st_nearest_feature(x, y) 会为 x 中的每个要素返回 y 中最近要素的索引。将它与 st_distance() 结合使用,可以同时获得最近邻要素及其距离,这对分配问题很有用。
library(sf)
# Hospitals (facilities)
hospitals <- data.frame(
name = c('Hospital A', 'Hospital B', 'Hospital C'),
lon = c(-79.5, -80.2, -78.8),
lat = c(35.8, 35.3, 36.1)
)
hosp_sf <- st_as_sf(hospitals, coords = c('lon', 'lat'), crs = 4326)
# Patient locations
patients <- data.frame(
id = 1:5,
lon = c(-79.9, -80.5, -79.0, -78.5, -80.1),
lat = c(35.7, 35.2, 35.9, 35.5, 36.0)
)
pt_sf <- st_as_sf(patients, coords = c('lon', 'lat'), crs = 4326)
# Find nearest hospital for each patient
nearest_idx <- st_nearest_feature(pt_sf, hosp_sf)
pt_sf$nearest_hospital <- hospitals$name[nearest_idx]
print(st_drop_geometry(pt_sf))实用工作流程:缓冲并计数
一种常见的实际应用模式是:先为一组要素(例如学校)创建缓冲区,然后使用 st_join() 和 dplyr::count() 统计每个缓冲区内有多少个兴趣点(例如公交车站)。
library(sf)
library(dplyr)
# Schools as points
schools <- data.frame(
id = 1:3,
lon = c(-79.8, -80.2, -79.4),
lat = c(35.9, 35.5, 36.1)
)
schools_sf <- st_as_sf(schools, coords = c('lon', 'lat'), crs = 4326) |>
st_transform(32119) # project to metres
# Random bus stops
set.seed(5)
stops <- data.frame(
stop_id = 1:50,
lon = rnorm(50, -79.8, 0.3),
lat = rnorm(50, 35.8, 0.2)
) |>
st_as_sf(coords = c('lon', 'lat'), crs = 4326) |>
st_transform(32119)
# 2 km buffer around each school
buffers <- st_buffer(schools_sf, dist = 2000)
buffers$school_id <- schools$id
# Count bus stops within each school buffer
joined <- st_join(stops, buffers['school_id'])
counts <- count(st_drop_geometry(joined), school_id)
cat('Bus stops within 2km:\n')
print(counts)快速检查
您想找出图层 B 中与图层 A 的每个多边形重叠的所有多边形要素,并将 B 的属性附加到 A。应该使用哪个函数?
回顾:空间连接与操作
要点:
st_join(x, y)——使用谓词执行空间左连接(默认值:st_intersects)st_within()——当 x 完全位于 y 内时返回 TRUE(不包括边界)st_intersects()——当 x 的任意部分接触 y 时返回 TRUE(限制最宽松)st_buffer(sf_obj, dist)——创建缓冲区;要获得以米为单位的准确缓冲区,请使用投影 CRSst_area()/st_distance()——计算面积和距离(为确保准确,请先进行投影)st_union()——融合所有要素;st_intersection()——将一个图层裁剪到另一个图层st_nearest_feature(x, y)——查找最近邻要素
library(sf)
nc <- st_transform(
read_sf(system.file('shape/nc.shp', package = 'sf')), 32119
)
# Quick operations summary
cat('Largest county:', nc$NAME[which.max(st_area(nc))], '\n')
nc_outline <- st_union(nc)
cat('State area km2:', round(as.numeric(st_area(nc_outline)) / 1e6, 0), '\n')常见问题解答
「空间连接与空间操作」课时是免费的吗?
是的 — 「空间连接与空间操作」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 R Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。
「空间连接与空间操作」这节课中我会学到什么?
应用 st_join()、st_intersection()、st_buffer() 和 st_distance() 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 R Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「空间连接与空间操作」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 R Academy 课中编写并运行代码吗?
能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。