如何在R语言中获取向量的所有连续子集?
To generate only the consecutive element subsets of your vector (excluding non-consecutive ones like {"test1", "test3"}), you don’t need to filter the full power set—instead, you can directly generate these valid subsets by focusing on contiguous index ranges. Here’s how to do it with the sets package (matching your original workflow):
Step-by-Step Solution
1. Set up your environment and vector
First, load the required package and define your input vector:
library(sets) v <- c("test1", "test2", "test3", "test4")
2. Generate consecutive subsets directly
We’ll create subsets by iterating over all possible contiguous index ranges. This avoids generating non-consecutive subsets entirely:
n <- length(v) consecutive_sets <- as.set(list()) # Start with the empty set # Iterate over all possible subset lengths (1 to full vector length) for (subset_length in 1:n) { # For each length, find all valid starting positions for (start_idx in 1:(n - subset_length + 1)) { end_idx <- start_idx + subset_length - 1 # Extract the contiguous subvector and convert to a set current_subset <- as.set(v[start_idx:end_idx]) # Add to our collection of consecutive sets consecutive_sets <- set_union(consecutive_sets, current_subset) } }
3. View the result
When you print consecutive_sets, you’ll get only the valid consecutive subsets:
consecutive_sets
Output:
{{}, {"test1"}, {"test2"}, {"test3"}, {"test4"}, {"test1", "test2"}, {"test2", "test3"}, {"test3", "test4"}, {"test1", "test2", "test3"}, {"test2", "test3", "test4"}, {"test1", "test2", "test3", "test4"}}
How This Works
- We start with the empty set (since your original power set included it).
- For each possible subset length (from 1 element up to the full vector), we calculate all valid starting positions where the subset fits within the vector.
- For each start position, we extract the contiguous elements (from start to
start + length -1) and convert it to a set. - We use
set_unionto add each new subset to our collection, ensuring no duplicates.
This approach is efficient because it only generates the subsets you need, instead of generating the full power set and filtering out unwanted ones.
内容的提问来源于stack exchange,提问作者vonjd

