2013-12-11 79 views
6

我有一組開始和結束的座標是這個樣子:轉換開始和結束座標到空間線中的R

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個線段的開始點到其相應的終點。我希望最終產品是對象,以便我可以在sp包中使用over函數。

回答

10

這裏有一個辦法:

## 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) 

這使得一個單獨的行對象(每一個獨特的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

人們還可以使用sf package打造sfc類的列表,然後將其轉換爲對象:

# 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