Reputation: 189
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.
Upvotes: 0
Views: 129
Reputation: 269371
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))
Upvotes: 3