Skip to content
Prev 360815 / 398506 Next

Ensure parameter is a string when passed within an lapply & called function runs a 'substitute' on it

Andrew:

Actually, thinking about it a bit more, I think my "solution" is not
really a solution either; that is, it will fail in use. My
understanding, which may be wrong and which others may correct, is
this: in the lapply call, x.var = ... will result in substitute(...)
in testFunc yielding an unevaluated call with my eval() "solution".
The problem is: when this call gets evaluated in testFunc() **where**
does it get evaluated? The answer is: in the testFunc environment
(lexical scoping); if not found there in the parent of testFunc, which
is the environment in which testFunc **was defined**, not called, and
so on up through the tree of frames. My solution works only because I
stuck "var" in the global environment, which happened to be where
testFunc was defined. This will not be true in general, and almost
certainly will fail for your actual use case.

I see no clean solution for this issue -- it's the nature of lexical
scoping. A simple way to make it work is just to stick var in the
.GlobalEnv or baseenv(), depending on where the function with
substitute comes from (but probably the latter). Then var will be
found by lexical scoping. e.g., for your example:

vars <- names(dataSet)

lapply(vars, function(var) {
  # print(paste('var', var))
  assign("somename",var,globalenv())
  testFunc(x = model, pred.data = dataSet, x.var =
eval(somename,globalenv()), plot = F)
})

I would hope someone else may offer a better approach.


Cheers,
Bert

Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Tue, May 10, 2016 at 11:17 AM, Bert Gunter <bgunter.4567 at gmail.com> wrote: