Search code examples
roptimizationtraveling-salesman

TSP in R, with given distances


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.


Solution

  • 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