R 中的 TSP,具有给定的距离
TSP in R, with given distances
5 个节点的简单距离 table,我想用它应用 TSP。在 Excel.
中打开时看起来像这样
library(TSP)
distances <- read.csv(file="c:\distances.csv", header=TRUE, sep=",")
distances <- as.dist(distances)
tsp <- TSP(distances)
tour <- solve_TSP(tsp)
tour
它在 as.dist() 行警告我:
Warning messages:
1: In storage.mode(m) <- "numeric" : NAs introduced by coercion
2: In as.dist.default(distances) : non-square matrix
还有 solve_TSP() 行:
Error in .solve_TSP(x, method, control, ...) : NAs not allowed!
我该如何更正它们?谢谢。
您需要将第一列设置为行标签(您目前将它们设置为一列)。下面的代码有效。
# Import distance matrix
library(readr)
distances <- read_csv("C:/distances.csv")
# Rename row labels
row.names(distances) <- distances$X1
distances$X1 <- NULL
# Run the TSP
distances <- as.dist(distances)
tsp <- TSP(distances)
tour <- solve_TSP(tsp)
tour
5 个节点的简单距离 table,我想用它应用 TSP。在 Excel.
中打开时看起来像这样library(TSP)
distances <- read.csv(file="c:\distances.csv", header=TRUE, sep=",")
distances <- as.dist(distances)
tsp <- TSP(distances)
tour <- solve_TSP(tsp)
tour
它在 as.dist() 行警告我:
Warning messages:
1: In storage.mode(m) <- "numeric" : NAs introduced by coercion
2: In as.dist.default(distances) : non-square matrix
还有 solve_TSP() 行:
Error in .solve_TSP(x, method, control, ...) : NAs not allowed!
我该如何更正它们?谢谢。
您需要将第一列设置为行标签(您目前将它们设置为一列)。下面的代码有效。
# Import distance matrix
library(readr)
distances <- read_csv("C:/distances.csv")
# Rename row labels
row.names(distances) <- distances$X1
distances$X1 <- NULL
# Run the TSP
distances <- as.dist(distances)
tsp <- TSP(distances)
tour <- solve_TSP(tsp)
tour