Search code examples
rpermutationsymbols

Varying Symbols of sign programmatically


I have a vector of numbers:

v1 <- c(1,2,3)

and I want to programmatically analyze the impact of sign change whose variants could be:

v1[1] + v1[2] + v1[3] 
[1] 6
v1[1] + v1[2] - v1[3] 
[1] 0
v1[1] - v1[2] - v1[3] 
[1] -4
v1[1] - v1[2] + v1[3] 
[1] 2

How can I exchange signs ('+', '-') programatically? I'm thinking this is a silly question, but can't think my way out of my box, though my line of analysis points to evaluating changing signs.


Solution

  • Here's a quick way to get all possibilities with matrix multiplication:

    signs = rep(list(c(1, -1)), length(v1))
    signs = do.call(expand.grid, args = signs)
    
    signs$sum = as.matrix(signs) %*% v1
    signs
    #   Var1 Var2 Var3 sum
    # 1    1    1    1   6
    # 2   -1    1    1   4
    # 3    1   -1    1   2
    # 4   -1   -1    1   0
    # 5    1    1   -1   0
    # 6   -1    1   -1  -2
    # 7    1   -1   -1  -4
    # 8   -1   -1   -1  -6
    

    If you don't want all combinations, you could filter down the signs data frame to the combos of interest, or build it in a way that only creates the combos you care about.