我在 R 中有两个数据框:
df1 <- data.frame(nelat = c(35.0, 35.2, 33.1, 32.0),
nelng = c(-106.8, -109.5, -110.6, -109.0),
swlat = c(33.7, 34.8, 32.7, 31.5),
swlng = c(-106.9, -109.9, -110.9, -109.3))
> df1
nelat nelng swlat swlng
1 35.0 -106.8 33.7 -106.9
2 35.2 -109.5 34.8 -109.9
3 33.1 -110.6 32.7 -110.9
4 32.0 -109.0 31.5 -109.3
df2 <- data.frame(snake = c("rattlesnake", "ratsnake", "cobra", "cobra", "python"),
lat = c(33.8, 36.0, 32.1, 33.0, 30.3),
lng = c(-106.8, -110.0, -110.7, -109.1, -110.1))
> df2
snake lat lng
1 rattlesnake 33.8 -106.8
2 ratsnake 36.0 -110.0
3 cobra 32.1 -110.7
4 cobra 33.0 -109.1
5 python 30.3 -110.1
我想将每行的 df1 的四个坐标组合成一个 sf 对象(本质上是一个边界框/矩形)。
我尝试了下面的代码,但出现错误。
df1_sf <- df1 %>%
st_as_sf(coords = c("swlng", "swlat", "nelng", "nelat"),
crs = 4326)
错误显示“points_rcpp(as.matrix(cc), dim) 中的错误: dim(pts)[2] == nchar(gdim) 不是 TRUE”
我的最终目标是计算每个 df1 矩形中有多少条来自 df2 的蛇。
关键点是你应该用
POLYGON
创建 st_polygon()
对象。这里至少需要5点。我编写 f()
函数来使用 df1
中的行创建它们。
library(dplyr)
library(ggplot2)
library(sf)
df1 <- data.frame(nelat = c(35.0, 35.2, 33.1, 32.0),
nelng = c(-106.8, -109.5, -110.6, -109.0),
swlat = c(33.7, 34.8, 32.7, 31.5),
swlng = c(-106.9, -109.9, -110.9, -109.3))
df2 <- data.frame(snake = c("rattlesnake", "ratsnake", "cobra", "cobra", "python"),
lat = c(33.8, 36.0, 32.1, 33.0, 30.3),
lng = c(-106.8, -110.0, -110.7, -109.1, -110.1))
# convert points in each row to polygon
f <- function(nelat, nelng, swlat, swlng){
m <- matrix(c(swlng, nelng, nelng, swlng, swlng,
swlat, swlat, nelat, nelat, swlat), nrow = 5)
return(st_polygon(list(m)))
}
df1 %>%
rowwise() %>%
mutate(geometry = list(f(nelat, nelng, swlat, swlng))) %>%
st_as_sf(sf_column_name = "geometry") %>%
ggplot() +
geom_sf() +
geom_point(data = df2, aes(x = lng, y = lat))