R中载体及其阴性的所有组合

Mag*_*loy 7 combinations r vector

如何找到矢量的所有组合,它在R中是否为负数?

IE

x <- c(1,2,3,4)
Run Code Online (Sandbox Code Playgroud)

将输出

(1,2,3,4), (-1,2,3,4), (1,-2,3,4), (1,2,-3,4), (1,2,3,-4), ... , (-1,-2,-3,-4)
Run Code Online (Sandbox Code Playgroud)

jos*_*ber 7

你可以使用do.callexpand.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
Run Code Online (Sandbox Code Playgroud)

代码lapply(1:4, function(x) c(x, -x))创建了向量的每个元素及其负数的列表; 在你的情况下,这将是list(c(1, -1), c(2, -2), c(3, -3), c(4, -4)).然后do.call将每个列表元素作为参数传递给expand.grid,返回所有可能的组合.

获取参数的一种稍微简单的方法可能是使用as.data.frame(rbind(x, -x))而不是lapply(x, function(y) c(y, -y)).


akr*_*run 7

或@ josilber解决方案的变体是

 expand.grid(Map(c, x, -x))
Run Code Online (Sandbox Code Playgroud)