luciano
luciano

Reputation: 13792

Find combinations of words in two vectors

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?

Upvotes: 5

Views: 122

Answers (2)

FXQuantTrader
FXQuantTrader

Reputation: 6891

You could use expand.grid.

sort(apply(X = expand.grid(x, y), MARGIN = 1, FUN = function(x) paste(x[1], x[2], sep = " ")))

Upvotes: 2

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

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" 

Upvotes: 6

Related Questions