Let's say I have a couple roots, prefixes, and suffixes.
roots <- c("car insurance", "auto insurance")
prefix <- c("cheap", "budget")
suffix <- c("quote", "quotes")
Is there a simple function or package in R which will allow me to construct all possible combinations of the three character vectors.
So I want a list, data frame, or vector which returns the following list of all possible combinations of each string.
cheap car insurance
budget car insurance
cheap car insurance quotes
cheap auto insurance quotes
auto insurance quote
auto insurance quotes
...
With something like 'auto insurance quotes', I'm using just the suffix and no prefix, so I need to get all possible results of those outcomes also.
expand.grid
is your friend:
expand.grid(prefix, roots, suffix)
Var1 Var2 Var3
1 cheap car insurance quote
2 budget car insurance quote
3 cheap auto insurance quote
4 budget auto insurance quote
5 cheap car insurance quotes
6 budget car insurance quotes
7 cheap auto insurance quotes
8 budget auto insurance quotes
Edited to include helpful comments by Prasad:
However, you will notice that your results are factors and not characters. To convert these factors into character vectors, you can use do.call
and paste
as follows:
do.call(paste, expand.grid(prefix, roots, suffix))
[1] "cheap car insurance quote" "budget car insurance quote"
[3] "cheap auto insurance quote" "budget auto insurance quote"
[5] "cheap car insurance quotes" "budget car insurance quotes"
[7] "cheap auto insurance quotes" "budget auto insurance quotes"
You can use a paste
function as an argument to outer
:
outer(prefix,outer(roots,suffix,paste),paste)
Output:
, , 1
[,1] [,2]
[1,] "cheap car insurance quote" "cheap auto insurance quote"
[2,] "budget car insurance quote" "budget auto insurance quote"
, , 2
[,1] [,2]
[1,] "cheap car insurance quotes" "cheap auto insurance quotes"
[2,] "budget car insurance quotes" "budget auto insurance quotes"
This can be reduced to a single vector using as.vector
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With