With get() call a function from an unloaded package without using library

此生再无相见时 提交于 2019-12-02 03:44:15

问题


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.


回答1:


Use getExportedValue:

getExportedValue("shiny",pagelist$type[1])("Display this text")
#<p>Display this text</p>



回答2:


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.



来源:https://stackoverflow.com/questions/45302215/with-get-call-a-function-from-an-unloaded-package-without-using-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!