Ken Williams
Ken Williams

Reputation: 23955

R expression from `nls` fit?

I've fit a parametric function using nls, and now I want to print out an expression of the function with the learned parameters substituted back in. For example:

x <- runif(100, 0, 100)
m <- 13 * exp(-0.05 * x^2) + 0.1 + runif(100,0,0.1)
mod <- nls(m ~ a*exp(-b*x^2)+c, start=list(a=10,b=0.1,c=0.1))

I can extract the formula and coefficients like so:

formula(mod)
# m ~ a * exp(-b * x^2) + c
coef(mod)
#           a           b           c 
# 13.00029360  0.04975388  0.14457936 

But I don't see a way to substitute them back directly. The only thing I can seem to do involves writing out the formula again:

substitute(m ~ a * exp(-b * x^2) + c, as.list(round(coef(mod), 4)))
# m ~ 13.0003 * exp(-0.0498 * x^2) + 0.1446

My ultimate goal here is to read a fitted nls object from an RDS file on disk and show its functional expression in an org-mode document.

Upvotes: 2

Views: 256

Answers (1)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162311

Is this what you're looking for?

do.call(substitute, args=list(formula(mod), as.list(round(coef(mod),4))))
# m ~ 13.0097 * exp(-0.0501 * x^2) + 0.1536

It works because do.call first evaluates both of the arguments in args and only then uses substitute() to substitute the coefficients into the formula expression. i.e., the expression that do.call() ultimately evaluates looks like this one, as desired:

as.call(list(substitute, formula(mod), as.list(round(coef(mod),4))))
# .Primitive("substitute")(m ~ a * exp(-b * x^2) + c, list(a = 13.0097, 
# b = 0.0501, c = 0.1536))

Upvotes: 4

Related Questions