do.call specify environment inside function

前端 未结 3 2104
盖世英雄少女心
盖世英雄少女心 2021-02-09 14:11

I\'m using the following construct in a package,

## two functions in the global environment
funa <- function(x) x^2
funb <- function(x) x^3
## called withi         


        
相关标签:
3条回答
  • 2021-02-09 14:17

    This seems to work, but i'm not sure if it has other implications I'm not considering:

    fun_wrap1 <- function(){
      funa1 <- function(x) x^2
      funb1 <- function(x) x^3
      lapply(c('funa1', 'funb1'), do.call, args=list(x=3), envir=environment())
    }
    
    fun_wrap1()
    #[[1]]
    #[1] 9
    #
    #[[2]]
    #[1] 27
    

    So this is essentially equivalent to having the lapply statement as:

    lapply(
           c('funa1', 'funb1'), 
           function(f) do.call(f, args=list(x=3), envir=environment() )
          ) 
    
    0 讨论(0)
  • 2021-02-09 14:25

    A slightly simpler version of @g-grothendieck's answer. Rather than using the function names, we just put the functions themselves into the list that is fed to lapply.

    fun_wrap1 <- function(){
      funa1 <- function(x) x^2
      funb1 <- function(x) x^3
      lapply(list(funa1, funb1), do.call, list(x=3))
    }
    
    fun_wrap1()
    
    0 讨论(0)
  • 2021-02-09 14:34

    Evidently if we evaluate the functions in fun_wrap2 it works. The problem with the approach in the question is that the character strings get converted to functions inside one of the processing functions which changes the lookup path.

    fun_wrap2 <- function(){
    
      funa1 <- function(x) x^2
      funb1 <- function(x) x^3
    
      nms <- c("funa1", "funb1")
      funs <- lapply(nms, match.fun)
      lapply(funs, do.call, list(x=3))
    
    }
    
    fun_wrap2()
    
    0 讨论(0)
提交回复
热议问题