【发布时间】:2016-04-19 11:17:54
【问题描述】:
惯用在 R 中进行以下字符串连接的方法是什么?
给定两个字符串向量,如下所示,
titles <- c("A", "B")
sub.titles <- c("x", "y", "z")
我要生成向量
full.titles <- c("A_x", "A_y", "A_z", "B_x", "B_y", "B_z")
显然,这可以通过两个 for 循环来完成。但是,我想知道 R 中的“惯用”(即优雅和自然)解决方案是什么。
在 Python 中,惯用的解决方案可能如下所示:
titles = ['A', 'B']
subtitles = ['x', 'y', 'z']
full_titles = ['_'.join([title, subtitle])
for title in titles for subtitle in subtitles]
R 是否允许类似程度的表现力?
备注
迄今为止提出的解决方案之间的共识是,在 R 中执行此操作的惯用方式基本上是,
full.titles <- c(t(outer(titles, sub.titles, paste, sep = "_")))
有趣的是,这在 Python 中有(几乎)字面翻译:
full_titles = map('_'.join, product(titles, subtitles))
product 是来自 itertools 模块的笛卡尔积函数。但是,在 Python 中,map 的这种用法被认为比上面的列表推导式的等效用法更复杂(即,更少表达)。
【问题讨论】:
-
@brittenb 未按问题要求生成向量。
-
@zacdav 是的,我现在正在查看输出,我很困惑为什么它没有产生预期的输出。我会删除评论。
-
有点直接翻译:mapply(function(x,y) sprintf("%s_%s", x, y), rep(titles, each=length(subtitles)), subtitles)跨度>
-
在这个例子中,R 比 Python 更“多彩”...想知道每个人都能想到多少种不同的方式...