# [R] Formula with dynamic number of variables

philippe massicotte pmassicotte at hotmail.com
Fri Nov 21 14:23:11 CET 2014

```Hi everyone.

I have a non-linear model specified as this (6 variables, a0, S, K, p0, p1, p2):

fit <- nlsLM(formula = dat ~ a0 * exp(-S*(x - 250)) + K + ( C ) )

where C = (p0*exp(-0.5*((x-p1)/p2)^2))

The problem is that I do not know in advance how many component (C) I will have in the model. That means It could be:

nlsLM(formula = dat ~ a0 * exp(-S*(x - 250)) + K + ( (p0*exp(-0.5*((x-p1)/p2)^2)) ) )

or

nlsLM(formula = dat ~ a0 * exp(-S*(x - 250)) + K + ( (p0*exp(-0.5*((x-p1)/p2)^2)) ) +   ( (p0b*exp(-0.5*((x-p1b)/p2b)^2)) ))

or

nlsLM(formula = dat ~ a0 * exp(-S*(x - 250)) + K + ( (p0*exp(-0.5*((x-p1)/p2)^2)) ) +   ( (p0b*exp(-0.5*((x-p1b)/p2b)^2)) +   ( (p0c*exp(-0.5*((x-p1c)/p2c)^2))))

So I was wondering if it was possible to dynamically build the formula that I will use in my model? The first part of my model will always be "a0 * exp(-S*(x - 250)) + K", I just want to add a certain number of "components" dynamically.

I guess it will be related with "reformulate()" but I can't not find how to make it works.