gpt4 book ai didi

r-从数据框中同一行中的两个点创建线串

转载 作者:行者123 更新时间:2023-12-04 15:24:56 25 4
gpt4 key购买 nike

我想知道是否有一种方法可以从新几何列中数据框中同一行中给定的两个点创建linestring。换句话说,两个点的经度和纬度在数据框中给出,如下所示:

df <- data.frame(id = c("a", "b"), lon1 = c(1,2), lat1 = c(3,4), lon2 = c(5,6), lat2 = c(7,8))  

其中 lon1lat1代表第一个点的坐标,而 lon2lat2是第二个点的坐标。所需的数据帧将具有两行两列- id列和 geometry列。

我尝试了 sf::st_linestring,但似乎此功能仅适用于矩阵。

所需的数据帧:
desired_df <- data.frame(id = c("a", "a", "b", "b"), lon = c(1,2,5,6), lat = c(3,4,7,8)) %>% st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4236) %>% group_by(id) %>% summarise(geometry = st_union(geometry), do_union = FALSE) %>% st_cast("LINESTRING")

最佳答案

更新-2021年1月30日
我原来的答案的问题是,它没有正确设置边界框。
今天,我将使用sfheadersdata.table使用这种方法

library(data.table)
library(sfheaders)

dt <- as.data.table(df)

## To use `sfheaders` the data needs to be in long form

dt1 <- dt[, .(id, lon = lon1, lat = lat1)]
dt2 <- dt[, .(id, lon = lon2, lat = lat2)]

## Add on a 'sequence' variable so we know which one comes first
dt1[, seq := 1L ]
dt2[, seq := 2L ]

## put back together
dt <- rbindlist(list(dt1, dt2), use.names = TRUE)
setorder(dt, id, seq)

sf <- sfheaders::sf_linestring(
obj = dt
, x = "lon"
, y = "lat"
, linestring_id = "id"
)

sf

# Simple feature collection with 2 features and 1 field
# geometry type: LINESTRING
# dimension: XY
# bbox: xmin: 1 ymin: 3 xmax: 6 ymax: 8
# CRS: NA
# id geometry
# 1 a LINESTRING (1 3, 5 7)
# 2 b LINESTRING (2 4, 6 8)


原始答案
一种使用 data.table的替代方法
要求(data.table)
dt <- as.data.table(df)

sf <- dt[
, {
geometry <- sf::st_linestring(x = matrix(c(lon1, lon2, lat1, lat2), nrow = 2, ncol = 2))
geometry <- sf::st_sfc(geometry)
geometry <- sf::st_sf(geometry = geometry)
}
, by = id
]

sf::st_as_sf(sf)
# Simple feature collection with 2 features and 1 field
# geometry type: LINESTRING
# dimension: XY
# bbox: xmin: 1 ymin: 3 xmax: 5 ymax: 7
# epsg (SRID): NA
# proj4string: NA
# id geometry
# 1 a LINESTRING (1 3, 5 7)
# 2 b LINESTRING (2 4, 6 8)

关于r-从数据框中同一行中的两个点创建线串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51918536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com