如何生成数值向量中2、3、4个元素组合的所有求和结果列表(R语言骰子向量示例)
Hey there! Let's walk through how to generate the list you need—including every element from your dice vector plus all possible sums of 2, 3, or 4 elements combined.
First, let's recap your setup: you've got a target value target.mountain <- 10 and generate your dice vector with Roll_dice <- sample(1:6, 4, replace=TRUE). For example, let's use your sample vector c(6,5,3,2) to demonstrate.
Step-by-Step Code
Here's a clean, straightforward way to get all the required sums in R:
# Your existing setup target.mountain <- 10 Roll_dice <- sample(1:6, 4, replace = TRUE) # Example vector (uncomment to test with your sample) # Roll_dice <- c(6,5,3,2) # Initialize a list to store sums for each combination size all_combo_sums <- list() # Loop through combination sizes 1 to 4 for (k in 1:4) { # Generate all unique combinations of k elements from Roll_dice combinations <- combn(Roll_dice, k) # Calculate the sum for each combination sum_per_combo <- colSums(combinations) # Add these sums to our list all_combo_sums[[k]] <- sum_per_combo } # Convert the list to a single vector (unsorted) unsorted_result <- unlist(all_combo_sums) # Optional: Sort the result to match your example's structure sorted_result <- sort(unsorted_result) # Print the sorted result print(sorted_result)
Example Output
Using your sample Roll_dice <- c(6,5,3,2), the sorted_result will look like this:
[1] 2 3 5 5 6 7 8 8 9 10 11 11 13 14 16
How It Works
combn(Roll_dice, k)generates every possible subset ofkelements from your dice vector. Fork=1, this is just each individual element.colSums(combinations)calculates the sum for each subset (sincecombnreturns subsets as columns).- We collect all these sums in a list, then unlist to get a flat vector. Sorting it gives the organized output you showed in your example.
If you don't need the sorted version, just use unsorted_result instead—it will include all values in the order of combination sizes (individual elements first, then 2-element sums, etc.).
内容的提问来源于stack exchange,提问作者KnowsNothingAboutCode

