Skip to content
Prev 324790 / 398503 Next

Trying to build up functions with its names by means of lapply

Rui et al.

Certainly correct.

However, I think the use of force() and similar should be avoided if
possible, as computing on the language can be tricky. So here is an
alternative formulation that avoids it:

faux <- function(c){
  f <- get(paste0(c,"gamma")) ## evaluation of c is forced here
  function(x)f(x,k,scale=theta)
}

Now another way to do this is:

faux <- function(c, nm = paste0(c,"gamma")){
     f <- get(nm)
      function(x)nm(x,k,scale=theta)}

This, in turn, suggests a more flexible function that would work for
any  distribution, using ... to pass in the arguments needed

faux <- function(c, nm = "gamma",...){
     f <- get(paste0(c,nm))
      function(x)f(x,...)
    }

This could be called with:
[1] 0.8710477
[1] 0.001265311


But it would also work for, e.g. "norm"
[1] 0.8413447
[1] 0.2419707

Cheers,
Bert

P.S. Bill Dunlap might have something to say about this. I think there
may be better ways to approach this whole business, but I prefer such
insight from real experts.

-- Bert
On Wed, Jun 5, 2013 at 2:58 AM, Rui Barradas <ruipbarradas at sapo.pt> wrote: