将开始和结束坐标转换为R中的空间线

时间:2013-12-11 22:15:06

标签: r spatial

我有一组开始和结束坐标,如下所示:

begin.coord <- data.frame(lon=c(-85.76,-85.46,-85.89), lat=c(38.34,38.76,38.31))
end.coord <- data.frame(lon=c(-85.72,-85.42,-85.85), lat=c(38.38,38.76,38.32))

我试图通过将每个起点连接到其对应的终点来创建一组3个线段。我希望最终产品是SpatialLines对象,以便我可以在over包中使用sp函数。

3 个答案:

答案 0 :(得分:12)

这是一种方式:

## raw list to store Lines objects
l <- vector("list", nrow(begin.coord))
library(sp)
for (i in seq_along(l)) {
    l[[i]] <- Lines(list(Line(rbind(begin.coord[i, ], end.coord[i,]))), as.character(i))
}

SpatialLines(l)

这会为每对创建一个单独的Lines对象(每个对象都有一个唯一的ID),否则您可能想要一个对象?

只是为了好玩,首先构建为spatstat psp对象,然后强制使用maptools中的方法:

library(spatstat)
p <- psp(begin.coord[,1], begin.coord[,2], end.coord[,1], end.coord[,2],     owin(range(c(begin.coord[,1], end.coord[,1])), range(c(begin.coord[,2], end.coord[,2]))))

library(maptools)
as(p, "SpatialLines") 

答案 1 :(得分:2)

还可以使用sf package构建sfc类列表,然后将其转换为SpatialLines对象:

# the given data
begin.coord <- data.frame(lon=c(-85.76,-85.46,-85.89), lat=c(38.34,38.76,38.31))
end.coord <- data.frame(lon=c(-85.72,-85.42,-85.85), lat=c(38.38,38.76,38.32))

library(sf)

# Create list of simple feature geometries (linestrings)
l_sf <- vector("list", nrow(begin.coord))
for (i in seq_along(l_sf)){
  l_sf[[i]] <- st_linestring(as.matrix(rbind(begin.coord[i, ], end.coord[i,])))
}
# Create simple feature geometry list column
l_sfc <- st_sfc(l_sf, crs = "+proj=longlat +datum=WGS84")

# Convert to `sp` object if needed
lines_sp <- as(l_sfc, "Spatial")

<强>附加/可选

# - create a sf object from the `sfc` list of linestrings
lines_sf = st_sf(id = 1:3, geometry = l_sfc)
# - visualize the `sfc` list of linestrings
plot(l_sfc)
library(mapview)
mapview(l_sfc, lwd = 5) 
# or mapview(lines_sp, lwd = 5)
# or mapview(lines_sf, lwd = 5)

enter image description here

答案 2 :(得分:2)

这几天(2020年),我会使用sfheaders

begin.coord <- data.frame(lon=c(-85.76,-85.46,-85.89), lat=c(38.34,38.76,38.31))
end.coord <- data.frame(lon=c(-85.72,-85.42,-85.85), lat=c(38.38,38.76,38.32))
begin.coord$linestring_id <- end.coord$linestring_id <- seq_len(nrow(begin.coord))
library(dplyr)

sfheaders::sf_linestring(bind_rows(begin.coord, end.coord) %>% arrange(linestring_id), 
                         x = "lon", y = "lat", linestring_id = "linestring_id")
#>   linestring_id                     geometry
#> 1             1 -85.76, -85.72, 38.34, 38.38
#> 2             2 -85.46, -85.42, 38.76, 38.76
#> 3             3 -85.89, -85.85, 38.31, 38.32

reprex package(v0.3.0)于2020-04-01创建