# [R] apply formula to data?

Gabor Grothendieck ggrothendieck at gmail.com
Tue May 11 15:09:48 CEST 2010

Is the problem that you want to use the formula as if it were a
function?  In that case:

1. nls2 in the nls2 package is like nls but its extensions include a
brute force algorithm which simply computes the formula at the
starting values:

> my.formula <- y ~ a+b*x^2
> y <- x <- 1:10
> library(nls2)
> fitted(nls2(my.formula, start = c(a = 2, b = 3), alg = "brute"))
[1]   5  14  29  50  77 110 149 194 245 302
attr(,"label")
[1] "Fitted values"

2. Also fn\$ in the gsubfn package can be used to convert a formula to
a function.  If there is no left hand side, LHS, then it is assumed
that the arguments are the free variables in the right hand side.  See

> library(gsubfn)
> fo <- my.formula
> fo[[2]] <- NULL  # zap LHS
> fn\$force(fo)
function (a, b, x)
a + b * x^2
> fn\$force(fo)(a = 2, b = 3, x = x)
[1]   5  14  29  50  77 110 149 194 245 302

On Tue, May 11, 2010 at 8:35 AM, ivo welch <ivowel at gmail.com> wrote:
> dear R wizards---
>
> I am looking for a reference that explains how to work with formula
> objects.  for example, say, I have a formula which I want to use in an
> NLS.  I want to test what this formula to see if my function was
> defined correctly.  Is there a way to apply a formula to data?  For
> example,
>
>   my.formula = (y ~ a+b*x^2)
>   x= 1:10; a=2; b=3;
>   computed.y= apply.a.formula( my.formula, x, a, b )
>
> I know that this has issues, not the least of which is that a formula
> may not return a y. and that  an lm() specification would require me
> to infer that I have an implicit coefficient vector that is not even
> specified (i.e., y~x really is y~a+b*x).  so, is there a reference to
> formula objects somewhere?
>
> sincerely,
>
> /iaw
> ----
> Ivo Welch (ivo.welch at brown.edu, ivo.welch at gmail.com)
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help