我想从一个数据框中创建一个sf对象,该数据框在每行的不同列下包含多个坐标。在下面的repex中,每个ID都包含纬度和经度的开始和结束坐标。

dfr <- structure(list(ID = c("1001A", "1002A", "1003A", "1004A", "1005A",
"1006A", "1007A", "1008A", "1009A", "1010A"), StartLat = c(33.53418,
33.60399, 33.40693, 33.64672, 33.57127, 33.42848, 33.54936, 33.49554,
33.5056, 33.61696), StartLong = c(-112.09114, -111.92731, -112.02982,
-111.92548, -112.04899, -112.0998, -112.09123, -111.9687, -112.05629,
-111.98657), EndLat = c(33.53488, 33.60401, 33.40687, 33.64776,
33.57125, 33.42853, 33.54893, 33.49647, 33.5056, 33.61654), EndLong = c(-112.09114,
-111.93097, -112.03429, -111.93031, -112.04807, -112.09929, -112.09122,
-111.97105, -112.0541, -111.98657)), row.names = c(3028L, 8618L,
6322L, 1171L, 691L, 6590L, 2008L, 4552L, 2894L, 1909L), class = "data.frame")我尝试使用sf包的st_as_sf函数,但产生了一个错误:
dfr_sf <- st_as_sf(dfr, coords = c(c("StartLong", "EndLong"), c("StartLat", "EndLat")),
crs = "+proj=longlat +datum=WGS84")Error in points_rcpp(as.matrix(cc), dim) :
dim(pts)[2] == nchar(gdim) is not TRUE每行中的起点和终点坐标定义了一个路段。所有坐标都应位于最终sf对象中的几何图形列下,以便这些坐标可以绘制为多段线。
发布于 2021-11-14 04:33:03
请查看dfr_line是否是您想要的。我认为我们首先需要创建一个point sf对象,然后将其转换为linestring。
library(tidyverse)
library(sf)
dfr2 <- dfr %>%
pivot_longer(-ID, names_to = c("Type", ".value"), names_pattern = "(^[A-Z][a-z]+)([A-Z][a-z]+$)")
dfr_point <- dfr2 %>%
st_as_sf(coords = c("Long", "Lat"), crs = "+proj=longlat +datum=WGS84")
dfr_line <- dfr_point %>%
group_by(ID) %>%
summarize() %>%
st_cast("LINESTRING")https://stackoverflow.com/questions/69960200
复制相似问题