[R] Using with() to avoid $ ?
bgunter.4567 at gmail.com
Mon Oct 24 08:22:31 CEST 2016
Bill et. al.
If I understand correctly, your example does not answer my query. I have
already acknowledged that the data argument is required for nse formula
evaluation. The question is: can with() also be used to evaluate other
arguments, some of which also might be in the formula's environment?. Both
Duncan and Jeff say this is asking for trouble. My query is: give me an
example of such trouble.
On Oct 24, 2016 12:50 AM, "William Dunlap" <wdunlap at tibco.com> wrote:
> 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>
>> 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
>> in foo are also sometimes needed as further arguments of f, and these
>> to be explicitly and tediously given as foo$whatever or equivalent
>> 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
>> Please correct any misstatements of fact in the above as well as
>> anything else I seem confused about.
>> Many thanks.
>> [[alternative HTML version deleted]]
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> PLEASE do read the posting guide http://www.R-project.org/posti
>> and provide commented, minimal, self-contained, reproducible code.
[[alternative HTML version deleted]]
More information about the R-help