2011-06-06 132 views
3

假設我有幾個根,前綴和後綴。查找三個字符串的所有可能組合

roots <- c("car insurance", "auto insurance") 
prefix <- c("cheap", "budget") 
suffix <- c("quote", "quotes") 

是否有R中一個簡單的函數或包,這將允許我構造 三個字符向量的所有可能組合。

所以我想要一個列表,數據框或向量,它返回以下列表 每個字符串的所有可能的組合。

cheap car insurance 
budget car insurance 
cheap car insurance quotes 
cheap auto insurance quotes 
auto insurance quote 
auto insurance quotes 
... 

的東西,如「汽車保險報價」,我只使用後綴和任何前綴,所以我需要得到這些結果的所有可能結果也。

回答

21

expand.grid是你的朋友:

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 

編輯者普拉薩德包括有益的意見:

但是,你會發現,你的結果的因素,而不是字符。這些因素轉化爲特徵向量,就可以使用do.callpaste如下:

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" 
+2

+1,你可以說'do.call(paste,expand.grid(...))'產生一個字符串向量作爲OP想要的。 – 2011-06-06 16:09:48

+0

謝謝,Prasad。我修改了答案來反映這一點。 – Andrie 2011-06-06 16:13:55

+0

這對我來說看起來像MadLibs。 :) – Iterator 2011-10-26 19:53:59

5

可以使用paste函數作爲參數傳遞給outer

outer(prefix,outer(roots,suffix,paste),paste) 

輸出:

, , 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" 

這可以使用as.vector簡化爲單個向量。

相關問題