r - Putting user-defined on a list in for loop -


i have problems storing user defined functions in r list when put on in loop.

i have define segment-specific functions based on parameters, create functions , put them on list looping through segments for-loop. problem same function everywhere on result list.

the code looks this:

n <- 100 segmenty <- 1:n segment_functions <- list() (i in segmenty){    segment_functions[[i]] <- function(){return(i)} } 

when run code same function (last created in loop) indexes:

## k segment_functions[[k]]() [1] 100  

there no problem when put functions on list manually e.g.

   segment_functions[[1]] <- function(){return(1)}    segment_functions[[2]] <- function(){return(2)}    segment_functions[[3]] <- function(){return(3)} 

works fine.

i honsetly have no idea what's wrong. help?

you need use force function ensure evaluation of i done during assignment list:

n <- 100 segmenty <- 1:n segment_functions <- list()  f <- function(i) { force(i); function() return(i) }  (i in segmenty){   segment_functions[[i]] <- f(i) } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -