Generate all possible combinations of a text string with two specific letters substituted for each other in R

Viewed 105

Using R, I have generated several strings of letters that range from 6-25 characters. I'd like for each one to generate an output that consists of all the combinations of these strings with every "I" substituted for a "L" and vice versa, the order of the characters should stay the same.

For example:

Input

"IVGLWEA"

OUTPUT

"IVGLWEA"
"LVGLWEA"
"LVGIWEA"
'IVGIWEA"
"LVGLWEA"

many thanks

rob

2 Answers

Edit: Thanks to @Skaqqs for the dynamic solution!

string <- "IVGLWEA"

# find the number of I's and L's in the string 
n <- length(unlist(gregexpr("I|L", string)))
# make a grid of all possible combinations with this amount of I's and L's
df <- expand.grid(rep(list(c("I", "L")), n))

# replace I's and L's with %s
string_ <- gsub("I|L", "\\%s", string)
# replace %s with letters in grid
do.call(sprintf, as.list(c(string_, df)))

Result:

[1] "IVGIWEA" "LVGIWEA" "IVGLWEA" "LVGLWEA"

Here's an extremely inefficient (but concise!) approach:

Create all potential combinations of your input characters and use regex to extract the desired pattern.

pattern <- "(I|L)VG(I|L)WEA"
b <- c("I", "V", "G", "L", "W", "E", "A")

strings <- apply(expand.grid(rep(list(b), 7)), 1, paste0, collapse = "")
grep(pattern, strings, value = TRUE)
[1] "IVGIWEA" "LVGIWEA" "IVGLWEA" "LVGLWEA"
Related