[R] Weird feature when creating function lists with apply
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Wed Oct 10 13:34:59 CEST 2001
Uffe Høgsbro Thygesen <uht at dfu.min.dk> writes:
> Thanks, Peter and Prof. Ripley, for your helpful replies.
>
> Referring to Prof. Ripley's reply, when I do
>
> f3 <- function(a) substitute(function(x) a*x, list(a = a))
> f <- lapply(1:4, f3)[[1]]
>
> then f is not a function:
>
> > is.function(f)
> [1] FALSE
>
> but
>
> > is.function(eval(f))
> [1] TRUE
...
> I do still not understand what f is, then, except something that evaluates
> to a function. My conclusion is that I need to start my head, too, and
> understand this lazy evaluation.
This part is not about lazy evaluation. This is because substitute
returns an object of mode "call", sometimes called an "unevaluated
expression", (which is a bit unfortunate because there is also an
"expression" mode, of which it is not...)
You could try picking it apart:
> f[[1]]
function
> f[[2]]
$x
> f[[3]]
1 * x
> f[[3]][[1]]
*
[..etc..]
> g <- eval(f)
> g
function(x) a*x
!!! Now *that* is truly weird.... The "source" atribute for g is
getting set, seemingly out of nowhere, to something that should not be
part of f. (This is a bug, but some nasty trickery is involved in
these matters and if might be difficult to fix.)
However if we clear
> attributes(g)<-NULL
> g
function (x)
1 * x
you can see that g is the actual function, not the call to the
function creator.
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list