Skip to content
Prev 14154 / 398503 Next

Weird feature when creating function lists with apply

On Wed, 10 Oct 2001, [iso-8859-1] Uffe Høgsbro Thygesen wrote:

            
I don't think this is what you intended.

ll <- apply(as.array(1:4),1,f1)
ll
[[1]]
function(x) a*x
<environment: a6d374>

[[2]]
function(x) a*x
<environment: a6d09c>

[[3]]
function(x) a*x
<environment: a6dd60>

[[4]]
function(x) a*x
<environment: a6da88>

which is not what your comment implies.

And
[1] 4

shows why they differ.


1) This is a strange way to produce a list via arrays:
ll <- lapply(1:4, f1) is what is normally used.

2) I think what you really wanted was

f3 <- function(a) substitute(function(x) a*x, list(a = a))
lapply(1:4, f3)
[[1]]
function(x) 1 * x

[[2]]
function(x) 2 * x

[[3]]
function(x) 3 * x

[[4]]
function(x) 4 * x