首页 > 解决方案 > 尝试在 R 中运行 GA,在 if (any(x < 0)) { 中出现错误:需要 TRUE/FALSE 的缺失值

问题描述

我对 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 

关于我可能做错的任何建议?

谢谢

标签: rgenetic-algorithm

解决方案


发生代码中的错误是因为它在 x[2] 不存在时尝试查找它。

如果您阅读 GA 函数的 Rastrigin 示例小插图,对于 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))

推荐阅读