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?
CodePudding user response:
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"
>
CodePudding user response:
Try
> do.call(paste0, expand.grid(sides, center, sides))
[1] "aaXXXXXXXaa" "bbXXXXXXXaa" "ccXXXXXXXaa" "aaXXXXXXXbb" "bbXXXXXXXbb"
[6] "ccXXXXXXXbb" "aaXXXXXXXcc" "bbXXXXXXXcc" "ccXXXXXXXcc"