Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all possible combinations of a three strings

Tags:

string

r

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.

like image 317
ATMathew Avatar asked Nov 27 '22 07:11

ATMathew


2 Answers

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"
like image 150
Andrie Avatar answered Dec 19 '22 11:12

Andrie


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.

like image 26
James Avatar answered Dec 19 '22 10:12

James