Someshwar
Someshwar

Reputation: 1

Mutation Error and Crossover Error not working properly

library(GA)

# Define the problem
set.seed(123)
assets <- c("Asset 1", "Asset 2", "Asset 3", "Asset 4", "Asset 5", "Asset 6", "Asset 7", "Asset 8", "Asset 9", "Asset 10")
criteria <- c(0.5, 0.3, 0.2) # We want to select assets that meet this criteria

# Define the representation of the solution
n <- length(assets)
bin_rep <- function(...) rbinom(n, 1, 0.5) # Represent the solution as a binary string

# Define the fitness function
fitness <- function(x) {
  selected_assets <- assets[x == 1]
  selected_criteria <- sum(selected_assets == "Asset 1")/length(selected_assets) # Define the criteria we want to meet
  return(-abs(selected_criteria - criteria[1]) - abs(sum(selected_assets == "Asset 2")/length(selected_assets) - criteria[2]) - abs(sum(selected_assets == "Asset 3")/length(selected_assets) - criteria[3]))
}

# Define the genetic operators
mutation <- function(x) {
  idx <- sample(1:n, 1)
  x[idx] <- 1 - x[idx]
  return(x)
}
crossover <- function(parent1, parent2) {
  mask <- rbinom(n, 1, 0.5)
  child1 <- parent1 * mask + parent2 * (1 - mask)
  child2 <- parent2 * mask + parent1 * (1 - mask)
  return(list(child1, child2))
}

# Implement the GA
ga_result <- ga(type = "binary", fitness = fitness, nBits = n, 
                lower = rep(0, n), upper = rep(1, n), 
                mutation = mutation, crossover = crossover)

# Evaluate the results
selected_assets <- assets[ga_result@solution == 1]
selected_fitness <- fitness

`

I am getting these error. i dont know what to do Error in x[idx] <- 1 - idx : object of type 'S4' is not subsettable Called from: mutation(object, i) also in crossover Error in parent1 * mask : non-numeric argument to binary operator Called from: crossover(object, parents)

Upvotes: 0

Views: 45

Answers (0)

Related Questions