r - Creating functions in a for loop with lists -


i scratching head @ following problem:

i creating 2 functions inside loop parameters depend on dataframe. each function put inside list.

printing parameters inside loop shows eachh function defined. yet, when use outside of loop, last parameters used both functions. following example should make clearer.

dt <- data.frame(color = c("red", "blue"),                  = c(3,9),                  b = c(1.3, 1.8)) function_list <- list() (col in dt$color) {   <- dt$a[dt$color == col]   b <- dt$b[dt$color == col]    foo <- function(x) {       a*x^b   }   print(paste(col, foo(1)))   function_list[[col]] <- foo } 

[1] "red 3"

[1] "blue 9"

function_list[["red"]](1) 

[1] 9

function_list[["blue"]](1) 

[1] 9

to note, inspired following question: r nested loop write multiple functions , plot them

the equivalent solution assign , get works (my answer previous question).

the relevant values of a , b when call function , not when define it. way create list, taken global environment. solution create closures. i'd use map this, can same for loop:

funs <- map(function(a, b) function(x) a*x^b, = dt$a, b = dt$b)  print(funs) #[[1]] #function (x)  #a * x^b #<environment: 0x000000000a9a4298> # #[[2]] #function (x)  #a * x^b #<environment: 0x000000000a9a3728> 

notice different environments.

environment(funs[[1]])$a #[1] 3 environment(funs[[2]])$a #[1] 9  funs[[1]](1) #[1] 3 funs[[2]](1) #[1] 9 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -