假设我有一些词根,前缀和后缀。
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
...
像“汽车保险报价”这样的东西,我只使用后缀而没有前缀,所以我需要得到这些结果的所有可能结果。
答案 0 :(得分:23)
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
编辑包含Prasad的有用评论:
但是,您会注意到结果是因素而不是字符。要将这些因素转换为字符向量,您可以使用do.call
和paste
,如下所示:
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"
答案 1 :(得分: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
将其缩小为单个矢量。