如何从R

时间:2019-04-23 08:39:46

标签: r join indexing match traveling-salesman

编辑:添加了当前解决方案

我正在研究旅行推销员问题,并且正在使用求解器来计算最佳游览。我的线性求解器的输出为我提供了一条路线中带有拱门的表格,但是要绘制行程,我需要将所有位置按正确顺序链接的向量。是否有一种优雅的方法可以将这些拱门链接成一个游览?

一个解决方案是一系列(嵌套)联接/匹配,但是在我看来这不是一个优雅的解决方案。

# output of solver (where i = 'from' and j = 'to')
solution = data.frame(i = c(6, 4, 10, 7, 1, 9, 3, 2, 8, 5),
                j = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))

# transformation
??

# required output
tour = c(6, 1, 5, 10, 3, 7, 4, 2, 8, 9)

因此,我要寻找的输出是游览中的连接拱门(从i到j)的单链。

我当前的解决方案用于循环和匹配,如下所示:

# number of cities to visit
nCities = length(solution)

# empty matrix
tour = matrix(0, nCities, 2)

#first location to visit picked manually
tour[1, ] = solution[1, ]

# for loop to find index of next arch in tour
for(k in 2:nCities){
  ind = match(tour[k - 1, 2], solution[, 1])         
  tour[k, ] = solution[ind, ]
}
# output 'tour' is the solution but then sorted.

# I then take only the first column which is the tour
tour = tour[1, ]


但是,它看起来笨拙,当我尝试尽可能避免for循环时,我对此并不满意。另外,我怀疑还有更好的解决方案,最好使用base R函数。

0 个答案:

没有答案