在R语言中生成所有长度为n的二进制向量的最优方法问询
Great question! Generating all binary vectors of length n in R is a common task, and striking the right balance between computational efficiency and code readability depends a bit on how large n you're working with. Let's walk through the best approaches, ranked by their sweet spots:
1. Most Readable (Small n ≤ 15)
If n is small enough that 2^n doesn't blow up your memory (think n ≤ 15, giving 32768 vectors), expand.grid is your go-to. It's self-documenting and requires almost no mental overhead:
n <- 3 # Generate all combinations of 0/1 for n positions binary_df <- expand.grid(rep(list(0:1), n)) # Convert to a matrix (each row is a binary vector) binary_vectors <- as.matrix(binary_df) # Optional: Reverse columns to match "left-to-right" bit order (expand.grid varies last column fastest) binary_vectors <- binary_vectors[, ncol(binary_vectors):1]
Why this works: expand.grid creates a data frame of all possible combinations of the input lists (here, n copies of 0:1). Converting to a matrix gives you the row-wise binary vectors you need. The column reversal is just a cosmetic tweak to make the first column change slowest (like standard binary counting).
2. Balanced Efficiency & Readability (Medium n ≤ 20)
For medium-sized n where expand.grid starts to lag a bit, use R's low-level intToBits function. It's fast (since it's implemented in C) and the code is concise with a quick comment:
n <- 5 # Generate integers from 0 to 2^n - 1 all_integers <- 0:(2^n - 1) # Convert each integer to its binary bits, take first n bits, transpose to get rows as vectors binary_vectors <- t(matrix(intToBits(all_integers)[1:n, ], nrow = n))
Why this works: intToBits returns the binary representation of each integer as a raw vector. We extract the first n bits (since integers are stored with more bits than we need), arrange them into a matrix, then transpose so each row is a complete binary vector. This method is way faster than expand.grid for n ≥ 10, but still easy to follow.
3. Ultra-Efficient (Large n, Memory Permitting)
If you're pushing the limits of what fits in memory (say n ≤ 25, giving ~33 million vectors), use a vectorized matrix construction approach. It avoids data frame overhead and leverages R's fast vector operations:
n <- 4 # Initialize matrix with first column (alternating 0s and 1s) binary_vectors <- matrix(rep(0:1, each = 2^(n-1)), nrow = 2^n) # Fill remaining columns by repeating previous columns at half the interval for (i in 2:n) { binary_vectors[, i] <- rep(binary_vectors[, i-1], each = 2^(n - i)) }
Why this works: We build the matrix column by column. The first column has 2^(n-1) zeros followed by 2^(n-1) ones. Each subsequent column repeats the previous column's pattern twice as often, which exactly matches the pattern of binary counting. This is the fastest method for large n because it uses only vector repeats, no string manipulation or data frame conversions.
Critical Note for Large n
Remember that binary vectors grow exponentially:
- n=20 → 1,048,576 vectors (~16MB of integer data)
- n=25 → 33,554,432 vectors (~536MB)
- n=30 → 1,073,741,824 vectors (~16GB)
If n is larger than 25, you'll likely need an iterative approach (generating vectors one at a time) instead of storing all of them in memory at once.
内容的提问来源于stack exchange,提问作者Scott Gigante

