I want to call a function from an unloaded package by having the function name stored in a list.
Normally I would just use:
library(shiny)
pagelist <- list("type" = "p") # object with the function name (will be loaded from .txt file)
get(pagelist$type[1])("Display this text")
but since when writing a package you're not allowed to load the library I'd have to use something like
get(shiny::pagelist$type[1])("Display this text")
which doesn't work. Is there a way to call the function from the function name stored in the list, without having to load the library? Note that it should be possible to call many different functions like this (all from the same package), so just using e.g.
if (pagelist$type[1] == "p"){
shiny::p("Display this text")
}
would require a quite long list of if else statemens.
Use getExportedValue
:
getExportedValue("shiny",pagelist$type[1])("Display this text")
#<p>Display this text</p>
You shouldn't use getExportedValue
as was done in the accepted answer, because its help page describes the functions there as "Internal functions to support reflection on namespace objects." It's bad practice to use internal functions, because they can change in subtle ways with very little notice.
The right way to do the equivalent of shiny::p
when both "shiny"
and "p"
are character strings in variables is to use get
:
get("p", envir = loadNamespace("shiny"))
The loadNamespace
function returns the exported environment of the package; it's fairly quick to execute if the package is already loaded.
The original question asked
Is there a way to call the function from the function name stored in
the list, without having to load the library?
(where I think "library" should be "package" in R jargon). The answer to this is "no", you can't get any object from a package unless you load the package. However, loading is simpler than attaching, so this won't put shiny
on the search list (making all of shiny
visible to the user), it's just loaded internally in R.
A related question is why get("shiny::p")
doesn't work. The answer is that shiny::p
is an expression to evaluate, and get
only works on names.