1

I am trying to get an optimized order of 20 as per self-defined function f (see below). So, I am using GA package of R. While using ga() function I want to provide some initial suggestions (population) to the algorithm. The initial suggestion is in the same format as the function ga() demands. But I am getting an error. Here is my code.

library(GA)

f <- function(z) sum((z-c(20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3,2,1))^2) 

set.seed(123)
c1 <- c(1, 3, 4, 2, 5, 7, 6, 9, 10, 8, 11, 12, 13, 15, 14, 16, 17, 18, 19, 20)
sugg <- as.data.frame(c1)
sugg$c2 <- sample(c1, 20)
sugg$c3 <- sample(c1, 20)
sugg$c4 <- sample(c1, 20)
sugg$c5 <- sample(c1, 20)
sugg$c6 <- sample(c1, 20)
sugg$c7 <- sample(c1, 20)
sugg$c8 <- sample(c1, 20)
sugg$c9 <- sample(c1, 20)
sugg$c10 <- sample(c1, 20)
sugg$c11 <- sample(c1, 20)
sugg$c12 <- sample(c1, 20)
sugg$c13 <- sample(c1, 20)
sugg$c14 <- sample(c1, 20)
sugg$c15 <- sample(c1, 20)
sugg$c16 <- sample(c1, 20)
sugg$c17 <- sample(c1, 20)
sugg$c18 <- sample(c1, 20)
sugg$c19 <- sample(c1, 20)
sugg$c20 <- sample(c1, 20)

sugg <- as.matrix(sugg)

set.seed(123)
result <- ga(type = "permutation", fitness = f, min = c(1), max = c(20), maxiter = 100, suggestions = sugg)

> result <- ga(type = "permutation", fitness = f, min = c(1), max = c(20), maxiter = 100, suggestions = sugg)
Iter = 1  | Mean = 1312.72  | Best = 1804 
Error in crossover(object, parents) : 
  number of items to replace is not a multiple of replacement length

Can somebody help me explain why am I getting this error? When I don't provide the suggestion ga() runs fine.

user3664020
  • 2,980
  • 6
  • 24
  • 45

1 Answers1

0

Old question, but might help someone.

My problem is not the same as yours (for me suggestions doesn't seem to make a difference), but anyway this might help understand what's going on. From the code in the function:

  # check suggestions
  if(is.null(suggestions))
    { suggestions <- matrix(nrow = 0, ncol = nvars) }
  else
    { if(is.vector(suggestions)) 
        { if(nvars > 1) suggestions <- matrix(suggestions, nrow = 1)
          else          suggestions <- matrix(suggestions, ncol = 1) }
      else
        { suggestions <- as.matrix(suggestions) }
      if(nvars != ncol(suggestions))
        stop("Provided suggestions (ncol) matrix do not match number of variables of the problem!")
    }
Björn Backgård
  • 148
  • 1
  • 10