[英]Sort matrix of points in R to get a sequential vector for plotting the line on x-y plot
我有一個凸包的點列表,作為矩陣,如下所示:
[,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
我還有這些點的 xy 坐標列表(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, named, 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
似乎輸出了一些奇怪的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.