通过粘贴字符作为输入来创建函数

Create function by pasting characters as input

我想创建一个函数,其名称由输入给出。例如,在下面的函数中,我想用输入字符 model 粘贴 loglik.tree.,这样我就不需要为每种情况调用 if 语句。在这种情况下,变量 loglik.tree.xxx 是函数。

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)
}

感谢任何帮助。我试图为它找到解决方案,但我没有成功搜索。

粘贴模型字符串作为后缀,然后get该名称的函数。

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

match.fun 也可以:

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