R语言优化器循环求解多列CSV数据的实现方法问询
Hey there! Great question—refactoring your code to loop through those columns without copying and pasting is totally doable, and it’ll make your code way cleaner and easier to maintain. Let’s break this down into simple steps:
First, take all the code you wrote to solve for AVGA1 and turn it into a function. This way, you can pass in any column name (like AVGA2, AVGA3, etc.) and run the same logic without rewriting it.
Here’s an example of what that might look like (adjust based on your actual optimization code—this assumes you’re using a linear solver like lpSolve):
# Load any required packages first (do this once outside the function) library(lpSolve) run_optimization <- function(player_data, score_column, position_limits, salary_cap) { # 1. Extract the target score values from the column objective_scores <- player_data[[score_column]] # 2. Set up your constraints (adjust these to match your actual rules) # Example: Position constraints (e.g., 2 PG, 2 SG, 2 SF, 2 PF, 1 C) position_matrix <- model.matrix(~ Pos - 1, data = player_data) # Salary constraint salary_vector <- player_data$Salary # Combine constraints into a single matrix/direction/value set constraint_matrix <- rbind(position_matrix, salary_vector) constraint_directions <- c(rep("=", ncol(position_matrix)), "<=") constraint_values <- c(position_limits, salary_cap) # 3. Run the optimization lp_solution <- lp( direction = "max", objective.in = objective_scores, const.mat = constraint_matrix, const.dir = constraint_directions, const.rhs = constraint_values, all.bin = TRUE # Assuming you're selecting players (binary: 0=not selected, 1=selected) ) # 4. Return a structured result with key info return(list( target_column = score_column, total_score = lp_solution$objval, total_salary = sum(player_data$Salary[lp_solution$solution == 1]), selected_players = player_data[lp_solution$solution == 1, ] )) }
Pro tip: Make sure you use player_data[[score_column]] instead of player_data$AVGA1 everywhere—this lets you dynamically reference the column name passed into the function.
Next, grab all the column names you want to run the optimization on (from AVGA2 up to AVG500). You can do this using pattern matching or column indices:
# Load your player CSV first player_df <- read.csv("your_player_file.csv") # Option 1: Use pattern matching to get all columns starting with "AVGA" except "AVGA1" target_columns <- colnames(player_df)[grepl("^AVGA", colnames(player_df)) & colnames(player_df) != "AVGA1"] # Option 2: If columns are strictly ordered (E=AVGA1, F=AVGA2, ...), use indices # target_columns <- colnames(player_df)[6:ncol(player_df)] # Column 6 is F/AVGA2, adjust if needed
Now use lapply (or a for loop if you prefer more control) to run the optimization for each column and save the results:
# Define your optimization parameters (customize these to your rules!) pos_limits <- c(PG = 2, SG = 2, SF = 2, PF = 2, C = 1) salary_cap <- 50000 # Example salary cap # Run optimization for all target columns all_optimization_results <- lapply(target_columns, function(col) { # Print progress so you can track which column is being processed cat("Running optimization for:", col, "\n") run_optimization(player_df, col, pos_limits, salary_cap) }) # Name the result list with column names for easy lookup names(all_optimization_results) <- target_columns
If you want to handle potential errors (e.g., a column has missing data that breaks the solver), use a for loop with tryCatch:
all_optimization_results <- list() for(col in target_columns) { tryCatch({ cat("Processing column:", col, "\n") all_optimization_results[[col]] <- run_optimization(player_df, col, pos_limits, salary_cap) }, error = function(e) { cat("Error with", col, ":", e$message, "\n") all_optimization_results[[col]] <- NULL # Store NULL for failed runs }) }
You can also create a summary table to compare results across columns:
# Extract key metrics into a data frame summary_table <- data.frame( Column = target_columns, Total_Score = sapply(all_optimization_results, function(x) x$total_score), Total_Salary = sapply(all_optimization_results, function(x) x$total_salary) ) # Save the summary to CSV write.csv(summary_table, "optimization_summary.csv", row.names = FALSE) # Save selected players for a specific column (e.g., AVGA2) write.csv(all_optimization_results$AVGA2$selected_players, "AVGA2_selected_players.csv", row.names = FALSE)
内容的提问来源于stack exchange,提问作者Blimes

