R scope: force variable substitution in function without local environment

前端 未结 3 430
無奈伤痛
無奈伤痛 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:27

    Here are some approaches that use body<-

    You could use bquote

    handlers <- list()
    
    for (i in 1:6) {
      handlers[[paste0('h', i)]] <- function () {}
      body( handlers[[paste0('h', i)]]) <- bquote(message(.(i)))
    }
    
    handlers$h1
    ## function () 
    ##   message(1L)
    

    or substitute

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

提交回复
热议问题