Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a namespace and export a function into it?

Tags:

r

Is there a way to declare a namespace and export a function into it so that it can be accessed using ::, without creating a whole package?

The following works for ::: but not :::

ns <- namespace::makeNamespace("my_namespace")
assign("test",7, env=ns)
my_namespace:::test # Triple colon - works.
# [1] 7
my_namespace::test # Double colon - doesn't work.
# Error: 'test' is not an exported object from 'namespace:my_namespace'

Is there an alternative to assign that would make the last line work? (The goal is to be able to simulate a package while developing it, so other files can use it as if it is a complete package but it can be quickly reloaded using source rather than devtools::install.)

like image 471
andycraig Avatar asked Dec 22 '17 12:12

andycraig


1 Answers

base::namespaceExport(ns, ls(ns)) seems to work (of course you can also use a subset as the list of objects to export in the second argument). Use it once you have defined all the objects in the namespace that you wish to export:

ns <- namespace::makeNamespace("my_namespace")
assign("test", 7, env = ns)
base::namespaceExport(ns, ls(ns))

my_namespace::test

Output:

7
like image 53
cyberSingularity Avatar answered Sep 22 '22 07:09

cyberSingularity