# [R] Formula with dynamic number of variables

Sven E. Templer sven.templer at gmail.com
Sat Nov 22 20:00:57 CET 2014

```# 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:
> 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
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> 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