如何在R中创建字符串组合
Posted
技术标签:
【中文标题】如何在R中创建字符串组合【英文标题】:How to create combination of strings in R 【发布时间】:2021-12-16 00:56:35 【问题描述】:我有以下字符串:
center <- "XXXXXXX"
sides <- c("aa", "bb", "cc") # Could be longer than 3 members
# string length of members could be varied.
我想要做的是将sides
的成员附加到center
两端的字符串列表所有可能的组合,产生:
aaXXXXXXXaa
aaXXXXXXXbb
aaXXXXXXXcc
bbXXXXXXXbb
bbXXXXXXXaa
bbXXXXXXXcc
ccXXXXXXXcc
ccXXXXXXXaa
ccXXXXXXXbb
如何使用 R 实现这一目标?
【问题讨论】:
【参考方案1】:将expand.grid
和apply
与paste
一起使用:
> apply(expand.grid(sides, sides), 1, paste, collapse = center)
[1] "aaXXXXXXXaa" "bbXXXXXXXaa" "ccXXXXXXXaa" "aaXXXXXXXbb" "bbXXXXXXXbb" "ccXXXXXXXbb" "aaXXXXXXXcc" "bbXXXXXXXcc" "ccXXXXXXXcc"
>
或者:
> apply(expand.grid(sides, center, sides), 1, paste, collapse='')
[1] "aaXXXXXXXaa" "bbXXXXXXXaa" "ccXXXXXXXaa" "aaXXXXXXXbb" "bbXXXXXXXbb" "ccXXXXXXXbb" "aaXXXXXXXcc" "bbXXXXXXXcc" "ccXXXXXXXcc"
>
或者正如@Wimpel 提到的,您可以使用data.table::CJ
来获取组合:
> apply(data.table::CJ(sides, sides), 1, paste0, collapse = center)
[1] "aaXXXXXXXaa" "aaXXXXXXXbb" "aaXXXXXXXcc" "bbXXXXXXXaa" "bbXXXXXXXbb" "bbXXXXXXXcc" "ccXXXXXXXaa" "ccXXXXXXXbb" "ccXXXXXXXcc"
>
【讨论】:
【参考方案2】:试试
> do.call(paste0, expand.grid(sides, center, sides))
[1] "aaXXXXXXXaa" "bbXXXXXXXaa" "ccXXXXXXXaa" "aaXXXXXXXbb" "bbXXXXXXXbb"
[6] "ccXXXXXXXbb" "aaXXXXXXXcc" "bbXXXXXXXcc" "ccXXXXXXXcc"
【讨论】:
以上是关于如何在R中创建字符串组合的主要内容,如果未能解决你的问题,请参考以下文章