Data<-read.csv("C:/Users/Michał/Desktop/player22.csv")

RW_idx <- which(grepl("RW", Data$Positions))
ST_idx <- which(grepl("ST", Data$Positions))
GK_idx <- which(grepl("GK", Data$Positions))
CM_idx <- which(grepl("CM", Data$Positions))
LW_idx <- which(grepl("LW", Data$Positions))
CDM_idx <- which(grepl("CDM", Data$Positions))
LM_idx <- which(grepl("LM", Data$Positions))
CF_idx <- which(grepl("CF", Data$Positions))
CB_idx <- which(grepl("CB", Data$Positions))
CAM_idx <- which(grepl("CAM", Data$Positions))
LB_idx <- which(grepl("LB", Data$Positions))
RB_idx <- which(grepl("RB", Data$Positions))
RM_idx <- which(grepl("RM", Data$Positions))
LWB_idx <- which(grepl("LWB", Data$Positions))
RWB_idx <- which(grepl("RWB", Data$Positions))


#############

pop_init  <- list()

# Create a list of vectors to loop through
position_vectors <- list(RW_idx, ST_idx, GK_idx, CM_idx, LW_idx, 
                         CDM_idx, LM_idx, CF_idx, CB_idx, CAM_idx,
                         LB_idx, RB_idx, RM_idx, LWB_idx, RWB_idx)


position_vectors_list<-position_vectors

parents<-population
t_size=5
tournament_selection <- function(parents, t_size) {
  # Select t_size random parents
  random_parents_idx <- sample(nrow(parents), t_size, replace = FALSE)
  random_parents <- parents[random_parents_idx, ]
  
  # Evaluate the target function for each selected parent
  random_parents_fitness <- apply(random_parents, 1, target)
  
  # Select the best parent based on the target function value
  best_parent_idx <- which.max(random_parents_fitness)
  return(random_parents[best_parent_idx, ])
}

# Crossover function
crossover <- function(parent1, parent2) {
  # Choose a random crossover point
  crossover_point <- sample(2:(ncol(parent1) - 1), 1)
  
  # Swap the position vectors after the crossover point
  offspring1 <- c(parent1[1:crossover_point], parent2[(crossover_point + 1):ncol(parent1)])
  offspring2 <- c(parent2[1:crossover_point], parent1[(crossover_point + 1):ncol(parent2)])
  
  return(rbind(offspring1, offspring2))
}






mutate <- function(individual, position_vectors_list, probability = 0.09) {
  for (pos_idx in 1:length(position_vectors_list)) {
    if (runif(1) <= probability) {
      repeat {
        random_idx <- sample(position_vectors_list[[pos_idx]], 1)
        if (!random_idx %in% individual) {
          individual[pos_idx] <- random_idx
          break
        }
      }
    }
  }
  return(individual)
}

preserve_elites <- function(population, num_elites) {
  population_fitness <- apply(population, 1, target)
  elite_indices <- order(-population_fitness)[1:num_elites]
  elites <- population[elite_indices, ]
  return(as.matrix(elites))
}




initialize_individual <- function(position_vectors_list) {
  individual <- sapply(position_vectors_list, function(pos) sample(pos, 1))
  return(individual)
}

# Create initial population
n_rows <- 100
initial_population <- matrix(NA, n_rows, length(position_vectors))
for (i in 1:n_rows) {
  individual <- initialize_individual(position_vectors)
  initial_population[i, ] <- individual
}




# Define the target function
target <- function(parent_indices) {
  position_ratings <- c("RWRating", "STRating", "GKRating", "CMRating",
                        "LWRating", "CDMRating", "LMRating", "CFRating",
                        "CBRating", "CAMRating", "LBRating", "RBRating",
                        "RMRating", "LWBRating", "RWBRating")
  
  parent_data <- Data[parent_indices, ]
  ratings <- parent_data[position_ratings]
  ratings_log <- log(ratings)
  
  potential_minus_age <- parent_data$Potential - parent_data$Age
  log_value_eur_minus_wage_eur <- log(parent_data$ValueEUR) - log(parent_data$WageEUR)
  int_reputation <- parent_data$IntReputation
  
  # Apply constraints
  constraint_penalty <- 0
  if (sum(parent_data$ValueEUR) > 250000000) {
    constraint_penalty <- constraint_penalty + 200
  }
  if (sum(parent_data$WageEUR) > 250000) {
    constraint_penalty <- constraint_penalty + 200
  }
  if (any(ratings_log < 1.2)) {
    constraint_penalty <- constraint_penalty + 200
  }
  
  target_value <- -(rowSums(ratings_log) + potential_minus_age - log_value_eur_minus_wage_eur + int_reputation) + constraint_penalty
  
  return(target_value)
}

# Create a matrix to store the population
population <- as.matrix(population)




# Genetic algorithm parameters
population_size <- 100
num_generations <- 1000
tournament_size <- 5
num_elites <- 2


k<-mutate(initial_population,position_vectors_list)


for (gen in 1:num_generations) {
  # Preserve elites
  elites <- preserve_elites(population, num_elites)
  
  # Create an empty matrix to store offspring
  offspring_population <- matrix(NA, population_size - num_elites, ncol(population))
  
  # Perform crossover and mutation to generate offspring
  for (i in seq(1, population_size - num_elites, 2)) {
    # Select two parents using tournament selection
    parent1 <- tournament_selection(population, tournament_size)
    parent2 <- tournament_selection(population, tournament_size)
    
    # Perform crossover to generate offspring
    offspring <- crossover(parent1, parent2)
    
    # Mutate offspring
    offspring[1, ] <- mutate(offspring[1, ], position_vectors_list)
    offspring[2, ] <- mutate(offspring[2, ], position_vectors_list)
    
    # Add the generated offspring to the offspring population matrix
    offspring_population[i, ] <- as.numeric(offspring[1, ])
    offspring_population[(i + 1), ] <- as.numeric(offspring[2, ])
  }
  
  # Replace the old population with the offspring and elites
  population <- rbind(elites, offspring_population)
  
  # Calculate the fitness for the current population
  population_fitness <- apply(population, 1, target)
  
  # Get the best solution in the current population
  best_solution <- population[which.max(population_fitness), ]
  best_fitness <- max(population_fitness)
}

# Remove temporary variables
rm(offspring_population, population_fitness)

There is something wrong with the so called fittness in the above genetic algorithm in R. The issue is that the  apply(population, 1, target) returns the unusable matrix instead of what should be an evaluation of solution for each row. Adjust the whole GA and target function. Keep in mind, that each index in row  is bounded to specific element in position_vectors_list and the target function should be evaluated based on whole row, which is one offspring or parent. If possible, skip whatever is implemented as fittness without losing the purpouse of the whole GA optimization.Think about the whole code.