# In R, how to solve 3 simultaneous equations?

#### arun

##### New Member
Hi there,
I am using R for some estimation purposes. I am applying MLE, MME and MQLE and some other related techniques to estimated parameters.

Particularly, in my case, I have to solve 3 simultaneous equations in order to obtain the 3 parameter estimates under some of the methods stated above. I am using "optim" for optimization purposes for MLE, however I am struggling with solving simultaneous equations iteratively.

Any suggestion would be greatly appreciable!

thank you.

#### BGM

##### TS Contributor
One crude approach is to minimize the sum of squares:

Suppose you want to solve a set of simultaneous equations $$f_i(\mathbf{x}) = 0, i = 1, 2, \ldots, n$$

Then you may try to minimize $$\sum_{i=1}^n f_i(\mathbf{x})^2$$

#### Nathan G

##### New Member
library(nleqslv) works for me.. Here's an example for linear equations, but it also works for non-linear equations.

Code:
###############################################################################################
#
#				# solving nonlinear systems of equations requires library(nleqslv)
#
###################################################################################################

fun <- function(x) {
f <- numeric(length(x)) 					# read as:
f[1] <-  2*x[3]  + -2*x[2] + 3*x[1]  - 17					# 0 = 2z - 2y + 3x + 4
f[2] <-  3*x[3]  + 4*x[2]  + -3*x[1] + 5					# 0 = 3z + 4y - 3x + 3
f[3] <-  -1*x[3] + 2*x[2]  + 5*x[1]  - 25					# 0 = -z + 2y + 5x + 1
f
}
startx <- c(1,1,1) # start the answer search here
answers<-as.data.frame(nleqslv(startx,fun))  # answers["x"] = x,y,z are the solutions closest to startx if there are multiple solutions