1

I am building a simple ant colony optimization code in R, but I have a problem in compiling a function to obtain the optimum route for each ant using the "break" statement. There is always appear an error saying that "missing value where TRUE/FALSE needed" in my looping. Here is the code

rm(list = ls())

x = c(11.7057,17.4151,1.4992,14.9609,9.5711)
y = c(11.1929,10.7112,17.0964,12.2228,6.7928)
n = length(x)

m = 20
t = matrix(0.0001,ncol=n,nrow=n)
beta = 1
alpha = 5
miter = 100

d = matrix(c(rep(0,n*n)),ncol=n,byrow=FALSE)
for (i in 1:n){
  for (j in 1:n){
    d[i,j] = sqrt((x[i]-x[j])^2+(y[i]-y[j])^2)
  }
}
d

h = matrix(c(rep(0,n*n)),ncol=n,byrow=FALSE)
for (i in 1:n){
  for (j in 1:n){
    if (d[i,j]==0){
      h[i,j]=0
    }
    else{
      h[i,j]=1/d[i,j]
    }
  }
}
h

antour <- function(a1,a2,a3,a4,a5,a6,a7){
for (i in 1:m){
    mh = h
    for (j in 1:n-1){
      a = start_places[i,j]
      mh[,c(a)]=0
      temp = (t[c(a),]^alpha)*(mh[c(a),]^beta)
      q = sum(temp)
      p = (1/q)*temp
      r = runif(1)
      s = 0
      for (k in 1:n){
        s = s+p[k]
        start_places[i,j+1] = k
        if (r <= s){
          break
        }
        print(start_places)
      }
    }
  }
  new_places = start_places
}


for (i in 1:miter){
  start_places = matrix(c(rep(1,m)),ncol=1)
  tour = antour(a1=start_places,a2=m,a3=n,a4=h,a5=t,a6=alpha,a7=beta)
}

I expect that in the looping process, the start_places[i,j+1]=k when the value of r <= s and obtain the optimum route for each ant, but the actual output is an error always appears as follows

output is Error in if (r <= s) { : missing value where TRUE/FALSE needed
  • This is due to `r <= s` not being satisfied (i.e. one `r` or `s` is not numeric - `s` from the look of it). Also the variables declared in your function `antour` are actually not used in the function. You need to each change the name of the variables or of the function parameters (e.g. `antour <- function(start_places, m, ...)`). – Thomas Guillerme Feb 06 '19 at 07:03
  • Thank you for your response @ThomasGuillerme, I have changed the name of the variables into `antour <- function(start_places,m,n,h,t,alpha,beta)` but the error still appears as before. So, how to solve the matter if one of `r` or `s` is not numeric? I'm still new with R software, so it will very helpful if this error can be fixed. – Atina Ahdika Feb 06 '19 at 07:18
  • I'm not quiet sure what your function is supposed to do (maybe document it a bit more?) but from the look of it, `s` is not numeric because `j` is defined as `0` in the first iteration of `for (j in 1:n-1){`. You probably want that to be `for (j in 1:(n-1)){`. – Thomas Guillerme Feb 07 '19 at 03:39

0 Answers0