R语言中查找可重复元素组合(m可大于向量长度)
Oh right, I’ve run into this exact issue before! The base R combn() function only handles combinations without replacement, which is why it throws that n < m error when you try to pick more elements than are in your vector. What you’re looking for are combinations with replacement—and there are a couple of easy ways to get that in R.
Using the gtools Package (Simplest Method)
The gtools library has a dedicated combinations() function that supports replacement out of the box. Here's how to use it for your example:
First, install and load the package if you haven’t already:
install.packages("gtools") library(gtools)
Then generate your desired combinations:
combinations(n = 2, r = 3, v = letters[1:2], repeats.allowed = TRUE)
This will output the unordered combinations you want (each row is a unique group):
[,1] [,2] [,3] [1,] "a" "a" "a" [2,] "a" "a" "b" [3,] "a" "b" "b" [4,] "b" "b" "b"
If you want the transposed version (matching your example’s column-wise display), just wrap it in t():
t(combinations(n = 2, r = 3, v = letters[1:2], repeats.allowed = TRUE))
Which gives:
[,1] [,2] [,3] [,4] [1,] "a" "a" "a" "b" [2,] "a" "a" "b" "b" [3,] "a" "b" "b" "b"
Base R Alternative (No External Packages)
If you’d rather avoid installing extra packages, you can use expand.grid() to generate all possible ordered tuples, then filter down to unique sorted combinations:
x <- letters[1:2] m <- 3 # Generate every possible ordered tuple (including duplicates) all_tuples <- expand.grid(rep(list(x), m)) # Sort each row to normalize combinations, then keep only unique ones unique_combs <- unique(t(apply(all_tuples, 1, sort))) # Transpose to match your preferred output format t(unique_combs)
This will produce the exact same result as the gtools method.
Quick Note on the Math
For combinations with replacement, the number of unique groups is calculated by the formula (n + m - 1 choose m), where n is the length of your vector and m is the number of elements to pick. For your example (n=2, m=3), that’s (2+3-1 choose 3) = 4 choose 3 = 4—which perfectly matches the 4 combinations you expected.
内容的提问来源于stack exchange,提问作者Jian

