首页 > 解决方案 > 如何解决 seq.int(lower, upper) 中的错误:“to”的长度必须为 1

问题描述

我正在尝试运行下面的代码来使用 GA 包解决 TSP。我有一个错误问题,但我无法解决它,我在互联网上找不到线索。

install.packages("GA")
library(GA)
myData<-read.csv(file="c:/Users/KPC/Desktop/city_tour.csv",header=TRUE,sep=",",row.names = 1)
str(myData)
D<-as.matrix(myData)
print(D)
travelDistance <- function(tour, distMatrix) {
   tour <- c(tour, tour[1])
   route <- embed(tour, 2)[,2:1]
   sum(distMatrix[route])
}
tspFitness <- function(tour, ...) 1/travelDistance(tour, ...)
GA <- ga(type = "permutation", fitness = tspFitness, distMatrix = D,
           lower = 1, upper = attr(myData,"Size"), popSize = 50, maxiter = 5000,
           run = 500, pmutation = 0.2,seed=1234)
summary(GA)
print(GA@solution[1,])
plot(GA)
apply(GA@solution,1,travelDistance,D) 
mds <- cmdscale(myData)
x <- mds[, 1]
y <- -mds[, 2]
plot(x, y, type = "n", asp = 1, xlab = "", ylab = "")
abline(h = pretty(range(x), 10), v = pretty(range(y), 10),
col = "light gray")
tour <- GA@solution[1, ]
tour <- c(tour, tour[1])
n <- length(tour)
arrows(x[tour[-n]], y[tour[-n]], x[tour[-1]], y[tour[-1]],
length = 0.25, angle = 25, col = "red", lwd = 2)
text(x, y, labels(myData), cex=0.8)

在调用函数时

GA <- ga(type = "permutation", fitness = tspFitness, distMatrix = D,
           lower = 1, upper = attr(myData,"Size"), popSize = 50, maxiter = 5000,
           run = 500, pmutation = 0.2,seed=1234)

我收到这个错误,T^T

Error in seq.int(lower, upper) : 'to' must be of length 1

str(data) 的输出如下:

'data.frame':   10 obs. of  10 variables:
 $ Seoul  : int  0 140 237 325 29 267 302 16 158 454
 $ Daejeon: int  140 0 119 200 140 140 190 153 232 327
 $ Daegu  : int  237 119 0 87 247 172 70 253 262 321
 $ Busan  : int  325 200 87 0 333 202 44 340 339 300
 $ Incheon: int  29 140 247 333 0 257 314 25 188 442
 $ Gwangju: int  267 140 172 202 257 0 221 277 372 187
 $ Ulsan  : int  302 190 70 44 314 221 0 318 301 339
 $ Goyang : int  16 153 253 340 25 277 318 0 165 464
 $ Sokcho : int  158 232 262 339 188 372 301 165 0 556
 $ Jeju   : int  454 327 321 300 442 187 339 464 556 0

print(D) 的输出如下:

     Seoul Daejeon Daegu Busan Incheon Gwangju Ulsan Goyang Sokcho Jeju
Seoul       0     140   237   325      29     267   302     16    158  454
Daejeon   140       0   119   200     140     140   190    153    232  327
Daegu     237     119     0    87     247     172    70    253    262  321
Busan     325     200    87     0     333     202    44    340    339  300
Incheon    29     140   247   333       0     257   314     25    188  442
Gwangju   267     140   172   202     257       0   221    277    372  187
Ulsan     302     190    70    44     314     221     0    318    301  339
Goyang     16     153   253   340      25     277   318      0    165  464
Sokcho    158     232   262   339     188     372   301    165      0  556
Jeju      454     327   321   300     442     187   339    464    556    0

我该如何解决这个问题?

标签: r

解决方案


推荐阅读