Warm tip: This article is reproduced from stackoverflow.com, please click
optimization r traveling-salesman

TSP in R, with given distances

发布于 2020-06-27 16:07:48

A simple distances table of 5 nodes, I want to apply TSP with it. It looks like this when open in Excel.

enter image description here

library(TSP)

distances <- read.csv(file="c:\\distances.csv", header=TRUE, sep=",")
distances <- as.dist(distances)

tsp <- TSP(distances)
tour <- solve_TSP(tsp)
tour

It warns me on the as.dist() line:

Warning messages:
1: In storage.mode(m) <- "numeric" : NAs introduced by coercion
2: In as.dist.default(distances) : non-square matrix

Also the solve_TSP() line:

Error in .solve_TSP(x, method, control, ...) : NAs not allowed!

How can I correct them? Thank you.

Questioner
Mark K
Viewed
24
Monk 2019-08-16 21:08

You need to set your first column as the row label (you currently have them as a column). This code below works.

# 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