Reputation: 792
I basically want to do the exact same thing as Generating all combinations with unknown length or https://www.geeksforgeeks.org/print-all-permutations-with-repetition-of-characters/ but in R. These links show how to do it in C++ but not R.
Suppose I have letter "ABCD", how to print all permutations with repetition of characters in r?
Upvotes: 0
Views: 334
Reputation: 388972
Using gtools::permutations
:
string <- 'ABCD'
vec <- strsplit(string, '')[[1]]
result <- gtools::permutations(length(vec), length(vec), vec, repeats.allowed = TRUE)
head(result)
# [,1] [,2] [,3] [,4]
#[1,] "A" "A" "A" "A"
#[2,] "A" "A" "A" "B"
#[3,] "A" "A" "A" "C"
#[4,] "A" "A" "A" "D"
#[5,] "A" "A" "B" "A"
#[6,] "A" "A" "B" "B"
Upvotes: 2
Reputation: 34416
One option would be to use the RcppAlgos
package although there are at least a handful of other packages that have functions for this:
library(RcppAlgos)
res <- permuteGeneral(LETTERS[1:4], 4, TRUE)
head(res)
[,1] [,2] [,3] [,4]
[1,] "A" "A" "A" "A"
[2,] "A" "A" "A" "B"
[3,] "A" "A" "A" "C"
[4,] "A" "A" "A" "D"
[5,] "A" "A" "B" "A"
[6,] "A" "A" "B" "B"
nrow(res)
[1] 256
Upvotes: 2