How can I find all combinations of a vector and it's negatives in R?
如何找到矢量的所有组合,它在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)
3 个解决方案
#1
7
You could use do.call
and expand.grid
:
你可以使用do.call和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.
代码lapply(1:4,function(x)c(x,-x))创建向量的每个元素及其负数的列表;在你的情况下,这将是列表(c(1,-1),c(2,-2),c(3,-3),c(4,-4))。然后do.call将每个列表元素作为参数传递给expand.grid,它返回所有可能的组合。
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))
.
获取参数的一种稍微简单的方法可以是使用as.data.frame(rbind(x,-x))而不是lapply(x,function(y)c(y,-y))。
#2
7
Or a variant of @josilber's solution is
或@josilber解决方案的变体是
expand.grid(Map(c, x, -x))
#3
1
use library(gtools)
gtools::combinations(8,4, c(-4:-1,1:4))
#1
7
You could use do.call
and expand.grid
:
你可以使用do.call和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.
代码lapply(1:4,function(x)c(x,-x))创建向量的每个元素及其负数的列表;在你的情况下,这将是列表(c(1,-1),c(2,-2),c(3,-3),c(4,-4))。然后do.call将每个列表元素作为参数传递给expand.grid,它返回所有可能的组合。
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))
.
获取参数的一种稍微简单的方法可以是使用as.data.frame(rbind(x,-x))而不是lapply(x,function(y)c(y,-y))。
#2
7
Or a variant of @josilber's solution is
或@josilber解决方案的变体是
expand.grid(Map(c, x, -x))
#3
1
use library(gtools)
gtools::combinations(8,4, c(-4:-1,1:4))