如何解决对R中的点矩阵进行排序,以获得用于在x-y图上绘制线的顺序向量
我有一个凸包的点列表,作为矩阵,如下所示:
[,1] [,2]
[1,] 23 18
[2,] 7 1
[3,] 14 18
[4,] 24 1
[5,] 24 23
[6,] 10 11
[7,] 13 14
[8,] 9 7
[9,] 9 10
[10,] 12 11
[11,] 12 13
我还有这些点的x-y坐标列表(UPD:船体中的每个整数都对应于x和y索引)。现在,我想通过一个lines()
调用来绘制凸包。我如何“展开”点矩阵,使其看起来像这样:c(23,18,14,13,12,11,10,9,7,1,24)
?
解决方法
是否要从顶点1开始的图的路径?软件包igraph
可以做到这一点。
library(igraph)
g <- graph_from_data_frame(mat)
p <- all_simple_paths(g,from = V(g)[1],mode = "all")
以下给出了列表p
中所有路径的长度。我们正在寻找最长的时间。
lengths(p)
#[1] 2 3 4 5 6 7 8 9 10 11 2 3 4 5 6 7 8 9 10 11
从上述长度可以明显看出,它们是相同的路径,具有不同的起始顶点,最长的是列表p
中的最后一条和中间的一条。
p[[length(p)/2]]
#+ 11/11 vertices,named,from 0bc39f7:
# [1] 23 24 1 7 9 10 11 12 13 14 18
p[[length(p)]]
#+ 11/11 vertices,from 0bc39f7:
# [1] 23 18 14 13 12 11 10 9 7 1 24
数据
x <- textConnection('
23 18
7 1
14 18
24 1
24 23
10 11
13 14
9 7
9 10
12 11
12 13
')
mat <- read.table(x)
close(x)
,
UPD:这是我想出的(正确)解决方案:
require(data.table)
find.nodes <- function(nodes) {
exit.nodes <- which(duplicated(nodes[,1]))
nodes <- cbind(nodes[exit.nodes,ncol(nodes):1],nodes[exit.nodes-1])
setorder(nodes)
return(nodes)
}
nodes <- rbind(hull,hull[,2:1],use.names=FALSE)
setorder(nodes)
nodes <- find.nodes(nodes)
while (nrow(nodes) > 2) {
nodes <- find.nodes(nodes)
}
nodes <- nodes[1,]
nodes <- unique(as.integer(nodes))
nodes <- c(nodes,nodes[1])
nodes
Unit: milliseconds
expr min lq mean median uq max neval
igraph.fun(hull) 0.875800 0.910251 0.9785159 0.921701 0.952600 97.3383 10000
setnodes.fun(hull) 1.931201 1.989401 2.1007707 2.011601 2.054401 23.4761 10000
它比igraph
解决方案要慢。
顺便说一句,igraph::convex.hull$resverts
似乎输出了一些奇怪的结果。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。