Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All combinations of vector and its negatives in R

How can I find all combinations of a vector and it's negatives in R?

I.E.

x <- c(1,2,3,4)

will output

(1,2,3,4), (-1,2,3,4), (1,-2,3,4), (1,2,-3,4), (1,2,3,-4), ... , (-1,-2,-3,-4)
like image 343
Mag Ulloy Avatar asked Jan 26 '15 04:01

Mag Ulloy


People also ask

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).

How to find number of combinations in R?

Combinations. The number of possible combinations is C(n,r)=n! r! (n−r)!

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.

What does expand grid do in R?

expand. grid() function in R Language is used to create a data frame with all the values that can be formed with the combinations of all the vectors or factors passed to the function as argument.


2 Answers

You could use do.call and expand.grid:

do.call(expand.grid, lapply(x, function(y) c(y, -y)))
#    Var1 Var2 Var3 Var4
# 1     1    2    3    4
# 2    -1    2    3    4
# 3     1   -2    3    4
# 4    -1   -2    3    4
# 5     1    2   -3    4
# 6    -1    2   -3    4
# 7     1   -2   -3    4
# 8    -1   -2   -3    4
# 9     1    2    3   -4
# 10   -1    2    3   -4
# 11    1   -2    3   -4
# 12   -1   -2    3   -4
# 13    1    2   -3   -4
# 14   -1    2   -3   -4
# 15    1   -2   -3   -4
# 16   -1   -2   -3   -4

The code lapply(1:4, function(x) c(x, -x)) creates a list of each element of your vector and its negative; in your case this would be list(c(1, -1), c(2, -2), c(3, -3), c(4, -4)). Then do.call passes each of these list elements as arguments to expand.grid, which returns all possible combinations.

A slightly simpler way to get the arguments could be to use as.data.frame(rbind(x, -x)) instead of lapply(x, function(y) c(y, -y)).

like image 140
josliber Avatar answered Sep 25 '22 20:09

josliber


Or a variant of @josilber's solution is

 expand.grid(Map(c, x, -x))
like image 29
akrun Avatar answered Sep 25 '22 20:09

akrun