开发者

Evaluating variable within R loop

开发者 https://www.devze.com 2022-12-20 02:15 出处:网络
I\'m trying to iteratively generate some functions using a For Loop: # Create a list to hold the functions

I'm trying to iteratively generate some functions using a 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's not working as I hoped as the i value is not being evaluated within each function. I want to try and define the function to equal x * 1; x * 2; etc, but what I end up with is a function that is x * i; where i is 21.

I tried using the eval() function and that just resulted in x * eval(i) being st开发者_运维知识库ored.


Use a closure (a function that write 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)


Check this one:

# 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))

    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号