[R] returning functions inside lapply
Ali Tofigh
alix.tofigh at gmail.com
Tue Apr 24 23:13:05 CEST 2012
On Tue, Apr 24, 2012 at 16:57, Duncan Murdoch <murdoch.duncan at gmail.com> wrote:
>> I thought that
>> lapply calls f three times and returns a list with whatever f
>> returned. Is this not so?
>
> That is so. In each case, f creates a function that looks in its enclosing
> environment for the variable x to be returned.
>
> That enclosing environment is the evaluation frame of f, where x is the
> argument being passed.
>
> But x is never used in evaluating f, so the promise to evaluate x is never
> forced until you finally call one of those functions.
>
> That means x will refer to some internal variable in lapply (which sapply
> calls). You'll have 3 different promises to evaluate it, but they all
> evaluate to the same value.
Thank you Duncan for you reply! However, I'm not sure I understand
this last explanation. This is what I think you mean lapply does.
Pleas correct me if I'm wrong.
1) lapply uses the same variable name as the argument in my function
(in this case 'x')
2) lapply uses this 'x' variable to set up a bunch of unevaluated calls
3) finally, lapply evaluates all the calls. but at this point,
lapply's 'x' variable is set to the last element of the list that was
passed to it and all the unevaluated calls will now use this value as
their 'x'?
/Ali
More information about the R-help
mailing list