尝试在 R 中 运行 GA,在 if (any(x < 0)) { 中出现错误:缺少需要 TRUE/FALSE 的值

Trying to run GA in R, getting Error in if (any(x < 0)) { : missing value where TRUE/FALSE needed

我对 R 比较陌生,需要建立一个遗传算法来找到一个能产生一定数量素数的方程。

install.packages("GA")
install.packages("matlab")
library(GA)
library(matlab)

f <- function(x)
{
  #initialize fitness score
  score <- 0 
  #set test values for k
  k <- seq(from = 1, to = 100,by = 1)
  #test if the result of the formula (k^2 + ak + b) is a prime number using test k values
  for (i in k) {
    if (isprime(i ^ 2 + x[1] * i + x[2]) == 2) {
    score = score + 1
    }
  }
  #return fitness score
  return(score)
}

lbound <- 2
ubound <- 1000

GA <- ga(type="real-valued",fitness=f,popSize = 10,pcrossover = 0.8,pmutation = 0.1, maxiter=30, run=20, lower = lbound, upper = ubound)

当我尝试 运行 GA 部分时,出现以下错误:

> GA <- ga(type="real-valued",fitness=f,popSize = 10,pcrossover = 0.8,pmutation = 0.1, maxiter=30, run=20, lower = lbound, upper = ubound)

 Error in if (any(x < 0)) { : missing value where TRUE/FALSE needed 

对我可能做错的地方有什么建议吗?

谢谢

您的代码中出现错误是因为它试图在不存在的情况下查找 x[2]。

如果您阅读 Rastrigin 示例中的 GA 函数小插图,对于 2 个值,您需要 1. 指定一个具有 2 个输入的函数和 2. 在此函数上使用包装器

f <- function(x1,x2)
# two variables
{
  #initialize fitness score
  score <- 0 
  #set test values for k
  k <- seq(from = 1, to = 100,by = 1)
  #test if the result of the formula (k^2 + ak + b) is a prime number using test k values
  for (i in k) {
    if (isprime(i ^ 2 + x1 * i + x2) == 2) {
    score = score + 1
    }
  }
  #return fitness score
  return(score)
}

lbound <- 2
ubound <- 1000

GA <- ga(type="real-valued",
#the wrapper is here
fitness=function(x)f(round(x[1]),round(x[2])),
popSize = 10,
pcrossover = 0.8,pmutation = 0.1, maxiter=30, 
run=20, lower = rep(lbound,2), upper = rep(ubound,2))