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)
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).
Combinations. The number of possible combinations is C(n,r)=n! r! (n−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.
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.
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))
.
Or a variant of @josilber's solution is
expand.grid(Map(c, x, -x))
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