R scope: force variable substitution in function without local environment

前端 未结 3 431
無奈伤痛
無奈伤痛 2021-01-03 05:47

I\'m defining functions in a loop and trying to force evaluation of a loop variable without having to carry around a private environment.

Example: a set of functions

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 06:37

    Here are two ways. They are the same except for the ## line in each:

    formals<-

    handlers <- list()
    f <- function() message(i)
    for (i in 1:6) { 
       formals(f) <- list(i = i) ##
       handlers[[paste0('h', i)]] <- f 
    }
    

    trace

    handlers <- list()
    f <- function() message(i)
    for (i in 1:6) { 
       trace(f, bquote(i <- .(i)), print = FALSE) ##
       handlers[[paste0('h', i)]] <- f 
    }
    

提交回复
热议问题