0
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)

  • Hello and welcome to Stack Overflow. Have you read the vignette and reference manual for GA? It looks like the various mutation functions all expect a GA object and a vector representing the parents. Your mutation function has only one input so it being passed the GA object, which is not subsettable. – Paul Stafford Allen Feb 22 '23 at 11:37
  • https://cran.r-project.org/web/packages/GA/index.html links to the vignette and reference manual on that page. – Paul Stafford Allen Feb 22 '23 at 11:37
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 22 '23 at 12:24
  • i am not able to understand why i am getting this Error in x[idx] <- 1 - idx : object of type 'S4' is not subsettable – Someshwar Feb 22 '23 at 15:05

0 Answers0