[R-pkg-devel] Adding non-exported functions in an extra environment in new S4 object

Rainer M Krug Rainer at krugs.de
Thu Jan 21 11:50:43 CET 2016


Rainer M Krug <Rainer at krugs.de> writes:

> Hi
>
> I have a package named asm which contains many non-exported functions
> which are all starting with "for.eq.".
>
> I also have an S4 class ASM which, when a new object asm of class ASM is
> created by using the function newASM() (in the package asm) contains
> among other slots one sot with an environment called "equations"
> (including the definition of the function"equations" and "equations<-").
>
> Now in this function newASM() I want to copy all functions starting with
> "for.eq." into this environment.
>
> I have the following code:
>
>     ASM at equations <- new.env()
>     funs <- apropos("^for\\.eq\\.", mode="function")
>     for (fun in funs) {
>         assign(
>             gsub("for.eq.", "", fun),
>             get(fun),
>             ASM at equations
>         )
>     }
>
> outside the package I call it as follow:
>
> asm <- newASM()
>
> This worked fine when the functions "for.eq.*" were exported, but does
> not work anymore now that I don't export them anymore.
>
> This is a bit surprising to me, as the function newASM() is in the
> package and I assumed that inside of a package, all exported and
> non-exported functions are seen.
>
> My question:
>
> how can I add all functions starting with "for.eq." into the
> environment, irrespective if they are exported or not?

I found a solution:

--8<---------------cut here---------------start------------->8---
    funs <- grep(
        pattern = "for.eq.*",
        x = ls(
            getNamespace("asm"),
            all.names=TRUE
        ),
        value = TRUE
    )
    for (fun in funs) {
        assign(
            gsub("for.eq.", "", fun),
            get(fun, getNamespace("asm")),
            ASM at equations
        )
    }
--8<---------------cut here---------------end--------------->8---

It adds all objects starting with "for.eq." but this is fine with me.

Thanks,

Rainer

>
> Why I want to do this: I want to be able to have the functions
> encapsulated in the environment of the object asm as they are used in a
> simulation executed by the sim() function, which attaches the equations
> environment at the beginning and detaches it at the end.
>
> This enables me to have different simulation objects with different
> functions.
>
> Thanks,
>
> Rainer

-- 
Rainer M. Krug
email: Rainer<at>krugs<dot>de
PGP: 0x0F52F982
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 454 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-package-devel/attachments/20160121/ab1aa8ad/attachment.bin>


More information about the R-package-devel mailing list