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?
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.
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.
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).
The combn() function in R is used to return the combination of the elements of a given argument x taken m at a time.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With