如何在R语言中实现求和不超过34的数值分组?
Absolutely! You can definitely pull off this grouping logic in R. The example you shared uses a greedy approach—prioritizing bigger values first and filling groups until adding the next number would push the sum over your 34 threshold—and this is super straightforward to code by hand, or you can use dedicated packages for more polished, optimized solutions.
Manual Greedy Implementation
Here's a step-by-step way to replicate the exact grouping from your example:
- First, sort your array in descending order (since we want to place the largest values into groups first)
- Set up an empty list to hold your final groups
- Loop through each value, adding it to the first existing group where it won't make the total sum exceed 34. If no group can take it, create a new one.
# Your original input array x <- c(28,26,20,5,3,2,1) threshold <- 34 # Sort values from largest to smallest sorted_x <- sort(x, decreasing = TRUE) # Initialize an empty list for our groups groups <- list() for (val in sorted_x) { # Flag to check if we've added the value to a group added_to_group <- FALSE # Check each existing group for (i in seq_along(groups)) { if (sum(groups[[i]]) + val <= threshold) { groups[[i]] <- c(groups[[i]], val) added_to_group <- TRUE break # Move to the next value once we find a fit } } # If no existing group can take the value, make a new group if (!added_to_group) { groups <- c(groups, list(val)) } } # Rename groups to match your example labels names(groups) <- c("a", "b", "c") # Print the result groups
When you run this code, you'll get exactly the grouping you wanted:
$a [1] 28 5 1 $b [1] 26 3 2 $c [1] 20
Using a Dedicated Package (binpacking)
If you're working with larger datasets and want a more optimized solution (this problem is a classic bin packing problem), the binpacking package has built-in functions tailored for this task.
First, install and load the package:
install.packages("binpacking") library(binpacking)
Then use the bpack function to handle the grouping automatically:
# Run the bin packing algorithm packing_result <- bpack(sorted_x, threshold) # Convert the result into named groups like your example package_groups <- split(sorted_x, packing_result$bins) names(package_groups) <- c("a", "b", "c") package_groups
This will also return the same valid grouping. Keep in mind that bin packing has different algorithm variations, so you might get slightly different (but still valid) groupings depending on the method used, but the greedy approach in this package will align closely with your manual implementation.
内容的提问来源于stack exchange,提问作者Bort54

