What is the idiomatic way to do the following string concatenation in R?
Given two vectors of strings, such as the following,
titles <- c("A", "B")
sub.titles <- c("x", "y", "z")
I want to produce the vector
full.titles <- c("A_x", "A_y", "A_z", "B_x", "B_y", "B_z")
Obviously, this could be done with two for-loops. However, I would like to know what an “idiomatic” (i.e., elegant and natural) solution would be in R.
In Python, an idiomatic solution might look like this:
titles = ['A', 'B']
subtitles = ['x', 'y', 'z']
full_titles = ['_'.join([title, subtitle])
for title in titles for subtitle in subtitles]
Does R allow for a similar degree of expressiveness?
Remark
The consensus among the solutions proposed thus far is that the idiomatic way to do this in R is, basically,
full.titles <- c(t(outer(titles, sub.titles, paste, sep = "_")))
Interestingly, this has an (almost) literal translation in Python:
full_titles = map('_'.join, product(titles, subtitles))
where product
is the cartesian-product function from the itertools module. However, in Python, such a use of map
is considered more convoluted—that is, less expressive—than the equivalent use of list comprehension, as above.