Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find combinations of words in two vectors

Tags:

string

r

vector

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?

like image 691
luciano Avatar asked Jun 10 '13 16:06

luciano


People also ask

How do you find the combination of a vector?

The number of possible combinations of two vectors can be computed by multiplying all the successive elements of the first vector with the corresponding elements of the second vector.

What combination consists of two vectors?

A linear combination of two or more vectors is the vector obtained by adding two or more vectors (with different directions) which are multiplied by scalar values.

How do you make all combinations of a vector in R?

To create combination of multiple vectors, we can use expand. grid function. For example, if we have six vectors say x, y, z, a, b, and c then the combination of vectors can be created by using the command expand. grid(x,y,z,a,b,c).

What does Combn do in R?

The combn() function in R is used to return the combination of the elements of a given argument x taken m at a time.


1 Answers

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" 
like image 58
Simon O'Hanlon Avatar answered Nov 15 '22 05:11

Simon O'Hanlon