Create all combinations of letter substitution in string

  • A+

I have a string "ECET" and I would like to create all the possible strings where I substitute one or more letters (all but the first) with "X".

So in this case my result would be:

> result [1] "EXET" "ECXT" "ECEX" "EXXT" "EXEX" "ECXX" "EXXX" 

Any ideas as to how to approach the issue?

This is not just create the possible combinations/permutations of "X" but also how to combine them with the existing string.


Using the FUN argument of combn:

a <- "ECET"  fun <- function(n, string) {   combn(nchar(string), n, function(x) {     s <- strsplit(string, '')[[1]]     s[x] <- 'X'     paste(s, collapse = '')   } ) } lapply(seq_len(nchar(string)), fun, string = a) 
[[1]] [1] "XCET" "EXET" "ECXT" "ECEX"  [[2]] [1] "XXET" "XCXT" "XCEX" "EXXT" "EXEX" "ECXX"  [[3]] [1] "XXXT" "XXEX" "XCXX" "EXXX"  [[4]] [1] "XXXX" 

unlist to get a single vector. Faster solutions are probably available.

To leave your first character unchanged:

paste0(   substring(a, 1, 1),   unlist(lapply(seq_len(nchar(string) - 1), fun, string = substring(a, 2))) ) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: