use makeActiveBinding inside a package

夙愿已清 提交于 2021-02-11 08:50:41

问题


I simply need a R function like:

> la. <- function (envir = globalenv()) {ls(all = T, envir = envir) }`

with an active binding so I do need to type brackets

> makeActiveBinding('la', la., globalenv())

So that

> la
[1]  "la"  "la."

I now want to implement function la() and it bind la inside a package So that when I load the package, la is ready available.

How can I bind function la.() to the symbol la within the package environment?

What value shall I pass to the envir argument of function makeActiveBinding()

Thanks for any help


回答1:


This is probably something to do in the .onLoad function, something like this in your package:

NAMESPACE <- environment()

la. <- function(){ 
  ls(all = T, envir = globalenv())
}

.onLoad <- function(libname, pkgname) {
  makeActiveBinding("la", la., NAMESPACE)
}



回答2:


I think this should work:

Lets write two functions inside a package:

# function one
ll_ <- function(){
  ls(envir = globalenv(), all.names = TRUE)
}

# function two
l_ <- function(){
  ls(envir = globalenv(), all.names = FALSE)
}

then write your onLoad() function

# Runs when package is loaeded
.onLoad <- function(libname, pkgname) {
  ns <-  asNamespace(pkgname)
  makeActiveBinding("ll", ll_,  env = ns) 
  makeActiveBinding("l", l_,  env = ns) 
  namespaceExport(ns, c('ll','l'))
}

When loading your packages, commands l and ll. run functions l() and ll()

Finally, I am sure that by embedding all function in a list and playing with functionals, the definition of onLoad() may become much lighter

Thanks Romain for your suggestion



来源:https://stackoverflow.com/questions/54204187/use-makeactivebinding-inside-a-package

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