5

I have a long list of words contained in two vectors

The first vector looks like this:

x <- c("considerably", "much", "far")

The second vector looks like this:

y <- c("higher", "lower")

I need a vector returned, which lists possible combinations of words from each vector. Using x and y, I would need this vector returned

[1] "considerably higher" "considerably lower"  "much higher"         "much lower"         
[5] "far higher"          "far lower"

Therefore words in vector x must come before words in vector y. Is there a quick way of doing this?

luciano
  • 13,158
  • 36
  • 90
  • 130

2 Answers2

6

You could use outer with paste, I think that will be quite quick!

as.vector( t( outer( x , y , "paste"  ) ) )
# [1] "considerably higher" "considerably lower"  "much higher"        
# [4] "much lower"          "far higher"          "far lower" 
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
2

You could use expand.grid.

sort(apply(X = expand.grid(x, y), MARGIN = 1, FUN = function(x) paste(x[1], x[2], sep = " ")))
FXQuantTrader
  • 6,821
  • 3
  • 36
  • 67