Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create combination of strings in R

I have the following strings:

center <- "XXXXXXX"
sides <- c("aa", "bb", "cc") # Could be longer than 3 members
# string length of members could be varied.

What I want to do is to make list of string that append member of sides to the both end of center in all possible combinations, yielding in:

aaXXXXXXXaa
aaXXXXXXXbb
aaXXXXXXXcc

bbXXXXXXXbb
bbXXXXXXXaa
bbXXXXXXXcc

ccXXXXXXXcc
ccXXXXXXXaa
ccXXXXXXXbb

How can I achieve that with R?

like image 632
scamander Avatar asked Mar 02 '23 09:03

scamander


1 Answers

Use expand.grid and apply with paste:

> apply(expand.grid(sides, sides), 1, paste, collapse = center)
[1] "aaXXXXXXXaa" "bbXXXXXXXaa" "ccXXXXXXXaa" "aaXXXXXXXbb" "bbXXXXXXXbb" "ccXXXXXXXbb" "aaXXXXXXXcc" "bbXXXXXXXcc" "ccXXXXXXXcc"
> 

Or:

>  apply(expand.grid(sides, center, sides), 1, paste, collapse='')
[1] "aaXXXXXXXaa" "bbXXXXXXXaa" "ccXXXXXXXaa" "aaXXXXXXXbb" "bbXXXXXXXbb" "ccXXXXXXXbb" "aaXXXXXXXcc" "bbXXXXXXXcc" "ccXXXXXXXcc"
> 

Or as @Wimpel mentioned, you could use data.table::CJ to get the combinations:

> apply(data.table::CJ(sides, sides), 1, paste0, collapse = center)
[1] "aaXXXXXXXaa" "aaXXXXXXXbb" "aaXXXXXXXcc" "bbXXXXXXXaa" "bbXXXXXXXbb" "bbXXXXXXXcc" "ccXXXXXXXaa" "ccXXXXXXXbb" "ccXXXXXXXcc"
> 
like image 54
U12-Forward Avatar answered Mar 12 '23 14:03

U12-Forward