[R] Using with() to avoid $ ?

William Dunlap wdunlap at tibco.com
Mon Oct 24 00:50:18 CEST 2016


Here is a concrete example where with(data, fit(formula)) differs from
fit(formula, data):

> z1 <- function(myFormula, myData) lm(myFormula, data=myData)
> z2 <- function(myFormula, myData) with(myData, lm(myFormula))
> coef(z1(hp ~ wt, datasets::mtcars))
(Intercept)          wt
  -1.820922   46.160050
> coef(z2(hp ~ wt, datasets::mtcars))
Error in eval(expr, envir, enclos) : object 'hp' not found

You could fix this up by adding data=environment() to z2's call to lm,
but I suspect there are lots of other functions for which this would fail
to work correctly.



Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Sun, Oct 23, 2016 at 9:18 AM, Bert Gunter <bgunter.4567 at gmail.com> wrote:

> As has been noted oftimes on this list
> f( y ~ x1 + x2 + x3 + ... , data = foo,  ...)
>
> is much preferable to
> f( foo$y ~ foo$x1 + foo$x2 + foo$x3 + ...,  ...)
>
> (with no data argument), using nse = non-standard evaluation to set the
> environment for formula evaluation. However, as queries here recently
> demonstrate,  the formula variables (y, x1, x2, x3, ...) or other variables
> in foo are also sometimes needed as further arguments of f,  and these have
> to be explicitly and tediously given as foo$whatever or equivalent
> indexing.
>
> So my question is, can/should with() be used instead in the form
> with(foo, f( y ~ x1 + x2 + x3 + ... , data = foo,  ...))  with no explicit
> $ or indexing in ... variables?
>
> or even
> with(foo, f( y ~ x1 + x2 + x3 + ... ,  ...))
>
> with no data argument for nse or indexing, though this seems to me
> questionable in that it may affect the formula's  environment
> differently.(??)
>
> Please correct any misstatements of fact in the above as well as clarifying
> anything else I seem confused about.
>
> Many thanks.
>
> Bert
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list