Create all possible strings from a vector R

Viewed 63

I have a vector with four letters.

letter <- c('x', 'y', 'z', 'j')

I would like to create all possible strings composed of 20 letters, repeating my four ones.

I tried with combn() and the random package but I failed.

1 Answers

First of all, you should be aware that your computer may not able to hold that huge amont of strings (all combinations of 20 letters), e.g.,

> rep(strrep("a", 20), 4^20)
Error: cannot allocate vector of size 8192.0 Gb

However, if we have shorter strings, it seems still possible to do that.


Here are a couple of base R options that could produce all combinations

f1 <- function(n) {
    if (n == 1) {
        return(letter)
    }
    v <- Recall(n - 1)
    unlist(lapply(letter, paste0, v))
}

f2 <- function(n) {
    v <- letter
    for (k in 2:n) {
        v <- unlist(lapply(letter, paste0, v))
    }
    v
}

f3 <- function(n) {
    lst <- rep(list(letter), n)
    Reduce(function(x, y) do.call(paste0, expand.grid(x, y)), lst)
}


f4 <- function(n) {
    do.call(paste0, expand.grid(rep(list(letter), n)))
}

and the speed benchmarking is

> n <- 10

> microbenchmark(
+     f1(n),
+     f2(n),
+     f3(n),
+     f4(n),
+     times = 10L
+ )
Unit: milliseconds
  expr       min        lq      mean    median        uq       max neval
 f1(n)  434.0156  592.1137  650.2692  617.9684  688.4830  903.9767    10
 f2(n)  461.7505  604.7973  749.9571  725.1946  969.3452 1097.1925    10
 f3(n) 1086.2451 1458.1349 1615.1434 1585.8263 1661.5754 2105.3784    10
 f4(n) 1780.0759 1926.0896 2192.6231 2256.5225 2288.2689 2703.9856    10
Related