【发布时间】:2018-10-03 13:42:24
【问题描述】:
我想从道路网络中随机选择路段。我认为这不会太难,但我没有得到任何地方。 这个想法是从线路网络中采样道路(线路)的延伸。我希望这些伸展具有一定的长度,并且我希望从网络中随机选择这些伸展。 我找到了将 SpatialLines 分割成给定长度HERE 的段的方法,但这不允许随机进行,也不允许组合不同线段。 我可以使用 sp 包中的 spsample 来沿线以均匀的距离间隔点。然后我就可以随机选择一个点作为起点。从理论上讲,我认为应该可以将相邻点添加到一条线上,但我不知道该怎么做,也不知道当道路分裂时我将如何处理随机选择一个方向(2条线相交) .
这是一些数据。
data <- data.frame(
x = c(1,2,3,3,3,3,1,2,3),
y = c(1,2,2,3,4,5,4,4,4),
id = c(rep("A",6), rep("B",3))
)
#with Kyle Walker's functions I convert the points to lines
#https://rpubs.com/walkerke/points_to_line
library(sp)
library(maptools)
points_to_line <- function(data, long, lat, id_field = NULL, sort_field = NULL) {
# Convert to SpatialPointsDataFrame
coordinates(data) <- c(long, lat)
# If there is a sort field...
if (!is.null(sort_field)) {
if (!is.null(id_field)) {
data <- data[order(data[[id_field]], data[[sort_field]]), ]
} else {
data <- data[order(data[[sort_field]]), ]
}
}
# If there is only one path...
if (is.null(id_field)) {
lines <- SpatialLines(list(Lines(list(Line(data)), "id")))
return(lines)
# Now, if we have multiple lines...
} else if (!is.null(id_field)) {
# Split into a list by ID field
paths <- sp::split(data, data[[id_field]])
sp_lines <- SpatialLines(list(Lines(list(Line(paths[[1]])), "line1")))
# I like for loops, what can I say...
for (p in 2:length(paths)) {
id <- paste0("line", as.character(p))
l <- SpatialLines(list(Lines(list(Line(paths[[p]])), id)))
sp_lines <- spRbind(sp_lines, l)
}
return(sp_lines)
}
}
lines <- points_to_line(data = data,
long = "x",
lat = "y",
id_field = "id")
#plot it
ori.plot <- plot(lines, col = rep(c(1, 2), length.out = length(lines)), axes = T, main="original",
ylim=c(0,5), xlim=c(0,5))
这给了我一个简单的两条线的情节。
或者
或者
我可以将它分割成给定长度的片段,就像上面提到的那样(长度 = 0.3):
但这些线段仅限于一条线,并且不会从随机点开始。
有什么想法吗?
【问题讨论】: