Variable evaluation inside the loop R

I am trying to iteratively generate some functions using For Loop:

# Create a list to hold the functions funcs <- list() funcs[] # loop through to define functions for(i in 1:21){ # Make function name funcName <- paste( 'func', i, sep = '' ) # make function func = function(x){x * i} funcs[[funcName]] = func } 

However, it does not work, as I had hoped, since the value of I is not evaluated inside each function. I want to try to define a function equal to x * 1; x * 2; etc., but in the end I get the function x * i; where i am 21.

I tried to use the eval () function, and this just led to saving x * eval (i).

+3
source share
2 answers

Check this:

 # Create a list to hold the functions funcs <- list() funcs[] # loop through to define functions for(i in 1:21){ # Make function name funcName <- paste( 'func', i, sep = '' ) # make function func = paste('function(x){x * ', i,'}',sep = '') funcs[[funcName]] = eval(parse(text=func)) } 
+2
source

Use closure (a function that writes functions):

 multiply <- function(i) { force(i) function(x) x * i } funcs <- list() for(i in 1:21){ funcName <- paste( 'func', i, sep = '' ) funcs[[funcName]] = multiply(i) } # OR in one line, with lapply funcs <- lapply(1:21, multiply) 
+6
source

All Articles