Skip to content

Formula with dynamic number of variables

2 messages · Philippe Massicotte, Sven E. Templer

#
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.

Thank you for your help,
Philippe
1 day later
#
# fixed formula part:
f <- dat ~ a0 * exp(-S*(x - 250)) + K
# convert to character
f <- as.character(f)
# component:
C <- "(p0*exp(-0.5*((x-p1)/p2)^2))"
# number of components (defined randomly):
n <- sample(1:3, 1)
C <- rep(C, n)
# collapse:
C <- paste(C, collapse = "+")
# combine
f <- paste(f[2], f[1], f[3], "+", C)
as.formula(f)
# hope this helps.
# best, s

On 21 November 2014 at 14:23, philippe massicotte
<pmassicotte at hotmail.com> wrote: