r - binding a function to a list -
where missing something?
fun<-list() make.fun<-function(i) function(n) i+n (i in 1:3) fun[[i]]<-make.fun(i) fun[[1]](1)
if check fun assignment reference nested function (as expected):
> fun [[1]] function (n) + n <environment: 0x03adfad0> [[2]] function (n) + n <environment: 0x03ae0834> [[3]] function (n) + n <environment: 0x03ae0604> >
problem if check:
> fun[[1]](1) [1] 4 >
when expect 2! (clearly overwriting last value)
on other hand, if manually assign each element of list:
fun[[1]]<-make.fun(1) fun[[2]]<-make.fun(2) fun[[3]]<-make.fun(3)
i correct answer:
> fun[[1]](1) [1] 2 > fun[[2]](3) [1] 5 >
i workaround using do.call, can't realize interpreter assuming in first loop, or why do.call mandatory in case. when try:
fun<-list() make.fun<-function(i) function(n) i+n (i in 1:3) fun[[i]]<-do.call('make.fun',list(i))
i (as expected):
> fun[[1]](2) [1] 3
any clue? (it happens when using lists)
your question copy-paste of force
example doc. need do:
fun <- list() make.fun <- function(i) { force(i); function(n) i+n } (i in 1:3) fun[[i]] <- make.fun(i) fun[[1]](1) # [1] 2
relevant details ?force
:
force forces evaluation of formal argument. can useful if argument captured in closure lexical scoping rules , later altered explicit assignment or implicit assignment in loop or apply function.
Comments
Post a Comment