[R] Trouble embedding functions (e.g., deltaMethod) in other functions

Blaser Nello nblaser at ispm.unibe.ch
Fri Mar 22 14:13:45 CET 2013


Instead of NaN's, I get the error message: Error in eval(expr, envir, enclos) : object 'z' not found. The reason you get the NaN's is, because you defined z in your global environment. The deltaMethod doesn't find the z defined in your function. I don't know why or how to fix this. Somebody with more R experience could probably do this. But if you look at the source code of deltaMethod you can solve the problem in your specific case with these function.

deltaMethod2 <- function(object, g, vcov., z, ...){
  if (!is.character(g)) 
    stop("The argument 'g' must be a character string")
  if ((car:::exists.method("coef", object, default = FALSE) || (!is.atomic(object) && 
    !is.null(object$coefficients))) && car:::exists.method("vcov", 
                                                     object, default = FALSE)) {
    if (missing(vcov.)) 
      vcov. <- vcov(object)
    object <- coef(object)
  }
  para <- object
  para.names <- names(para)
  g <- parse(text = g)
  q <- length(para)
  for (i in 1:q) {
    assign(names(para)[i], para[i])
  }
  est <- eval(g)
  names(est) <- NULL
  gd <- rep(0, q)
  for (i in 1:q) {
    gd[i] <- eval(D(g, names(para)[i]))
  }
  se.est <- as.vector(sqrt(t(gd) %*% vcov. %*% gd))
  data.frame(Estimate = est, SE = se.est)
}
deltaSE <- function(mod, x){
  mod.SE <- list()
  for(i in 1:length(x)){
    z <- x[i]
    mod.SE[[i]] <- deltaMethod2(mod, g="(m0^(1/lambda) - (z * m0/t0)^(1/lambda))^lambda", z=z)$SE
  }
  mod.SE
}
deltaSE(nlls, xVal)


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of PatGauthier
Sent: Freitag, 22. März 2013 13:54
To: r-help at r-project.org
Subject: Re: [R] Trouble embedding functions (e.g., deltaMethod) in other functions

Ah Yes, good point. However, it still does not correct the situation. I still get NaN's. 



--
View this message in context: http://r.789695.n4.nabble.com/Trouble-embedding-functions-e-g-deltaMethod-in-other-functions-tp4662178p4662187.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list