GMM Estimation and convergence problem I try to minimize an unweighted moment function $G(\theta)$ given by $G(\theta) = \bar{g}(\theta)'\bar{g}(\theta) $. 
$g(\theta,x_i)$ contains the specified moment conditions, where we state $E(g(\theta_0, x_i))=0$ and $\bar{g}(\theta) = N^{-1}\sum_{i=1}^N g(\theta,x_i) $.
R provides a GMM tool with gmm() that works fine to handle the problem.
Example: 
Take the example in Chaussé (2010) where he presents the GMM estimation of the parameters of a normal distribution:
    library(gmm)

set.seed(123)
n <- 2000
x1 <- rnorm(n, mean = 4, sd = 2)

g1 <- function(tet,x)  # Moment function
{

  m1 <- (tet[1]-x)     # 1st moment E[mu - xi] = 0 
  m2 <- (tet[2]^2 - (x - tet[1])^2)  # 2nd moment E[sig^2 - ( x_i - mu)^2] = 0 

  m <- cbind(m1,m2) 
  return(m)
}

print(res <- gmm(g1,x1,c(mu = 0, sig = 0), optfct = "optim", wmatrix = "ident" , tol = 0.01 )  )

However, when specifying manually the unweighted moment function $G(\theta)$ and using an optimization tool like optim() estimates are far from the true values ($\mu = 4$ and $\sigma = 2$), as I run into convergence problems. 
Example: 
gg <- function(tet){


  gv <- as.matrix(colMeans(g1(tet, x = x1)))

  t(gv)%*%gv

}



start.values = c(0,0)
gg_est <- optim(start.values , gg, method = "BFGS", control = list(maxit = 10000, abstol = 0.01, reltol = 0.01) )
summary(gg_est)
gg_est$par

Any idea what I miss here? 
 A: To be precise, it is the second moment that you get wrong. The first first one is on spot. In your case, given that the moment conditions are correct (but the criterion function looks very messy to be honest), this has clearly to do with the chosen convergence procedure, the control parameters that you specified by hand, and/or the starting values given that you chose BFGS. Two solutions:

*

*If you want to keep your controls and BFGS as minimization method, choose (.1/.1) or something like that as starting values

*If you want to keep starting at 0/0, choose "Nelder-Mead" (which should be the default if you don't specify anything), but remove your manual control parameters (in your case your tolerance levels were choosen to high - if you want to do it "by hand"

Finally, for pedagogical reasons I would also suggest to clean up the code a bit and make it more structured. Something like this maybe?
GMM_moment_conditions <- function(theta, xvals) {
  mu <- theta[1]
  sigma <- theta[2]
  m1 <-  xvals - mu
  m2 <- (sigma^2 - (xvals - mu)^2)
  rbind(mean(m1), mean(m2))
}

GMM_criterion <- function(theta, xvals) {
  g_m <- GMM_moment_conditions(theta, xvals)
  W <- diag(2)
  t(g_m) %*% W %*% g_m
}

optim(par = c(mu = 0, sigma = 0), fn = GMM_criterion, xvals = x1)

