Search code examples
rsolverequation-solving

Solve indeterminate equation system in R


I have a equation system and I want to solve it using numerical methods. I want to get a close solution given a starting seed. Let me explain.

I have a vector of constants ,X, of values:

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

and a vector W of weights:

W <- (c(0.25,0.25,0.25,0.25))

I want that the sum of the components of W will be (sum(W)=1), and the sum of the multiplication of X and W element by element will be a given number N (sum(W*X)=N).

Is there a easy way to do this in R? I have it in Excel, using Solver, but I need to automatize it.


Solution

  • Here is your constant and your target value:

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

    You need a function to minimize. The first line contains each of your conditions, and the second line provides a measure of how to combine the errors into a single score. You may want to change the second line. For example, you could make one error term be more heavily weighted than the other using sum(c(1, 5) * errs ^ 2).

    fn <- function(w)
    {
      errs <- c(sum(w) - 1, sum(x * w) - n) 
      sum(errs ^ 2)
    }
    

    The simplest thing is to start with all the weights the same value.

    init_w <- rep.int(1 / length(x), length(x))
    

    Use optim to optimize.

    optim(init_w, fn)
    ## $par
    ## [1]  0.1204827 -1.2438883  1.1023338  1.0212406
    ## 
    ## $value
    ## [1] 7.807847e-08
    ## 
    ## $counts
    ## function gradient 
    ##      111       NA 
    ## 
    ## $convergence
    ## [1] 0
    ## 
    ## $message
    ## NULL
    

    The par element contains your weights.