Search code examples
rfunctionpastenames

Create function by pasting characters as input


I would like to create a function which name is given by an input. For instance, in the function below, I would like to paste loglik.tree. with the input character model, so I would not need to call an if statement for every case. In this case the variables loglik.tree.xxx are functions.

loglik.tree <- function(model){
  if(model == "rpd"){
    log.lik = loglik.tree.rpd
  }
  if(model == "dd"){
    log.lik = loglik.tree.dd
  }
  if(model == "edd"){
    log.lik = loglik.tree.edd
  }
  if(model == "pd"){ 
    log.lik = loglik.tree.pd
  }
  if(model == "epd"){ 
    log.lik = loglik.tree.epd
  }
  if(model == "gddx"){ 
    log.lik = loglik.tree.gddx
  }
  if(model == "gpdx"){ 
      log.lik = loglik.tree.gpdx
  }
  return(log.lik)
}

Any help is appreciated. I tried to find a solution for it, but I did not succeed searching.


Solution

  • Paste the model string as a suffix and then get the function of that name.

    get(paste0("loglike.tree.", model))
    

    match.fun would also work:

    match.fun(paste0("loglike.tree.", model))