Programmatically switch package in `::` call in R












8














I would like to be able in a call bar::foo(), to be able to programmatically switch the package bar so that the same syntax calls hello::foo().



An example:




  • Let's say I have three packages, parentPkg, childPkg1 and childPkg2.

  • In parentPkg I have a call to function childPkg1::foo()


  • foo() is also a function in childPkg2


  • I would like to be able, in parentPkg to use the :: operator to call foo() but to programatically switch the package name.
    Something like:



    dummy_pkg_name = ifelse(scenario=="child1", "childPkg1", "childPkg2")
    dummy_pkg_name::foo()



Is it possible? How do I achieve it?



Some context



parentPkg is a function that interacts with a web application, takes some request and data and returns results from different statistical models depending on the scenarios.

Each scenario is quite complex and not everything can be generalised in parentPkg. For this reason, childPkg1 and childPkg2 (actually there are also 3 and 4) are sort of sub-packages that deals with the data cleaning and various alternatives for each scenario but return the same class of value.

The idea is that parentPkg would switch the package to the pertinent child depending on the scenario and call all of the necessary functions without having to write the same sequence for each child but just with a slightly different :: call.










share|improve this question






















  • I think if(requireNamespace('childPkg1')) is what you really want
    – MichaelChirico
    4 hours ago
















8














I would like to be able in a call bar::foo(), to be able to programmatically switch the package bar so that the same syntax calls hello::foo().



An example:




  • Let's say I have three packages, parentPkg, childPkg1 and childPkg2.

  • In parentPkg I have a call to function childPkg1::foo()


  • foo() is also a function in childPkg2


  • I would like to be able, in parentPkg to use the :: operator to call foo() but to programatically switch the package name.
    Something like:



    dummy_pkg_name = ifelse(scenario=="child1", "childPkg1", "childPkg2")
    dummy_pkg_name::foo()



Is it possible? How do I achieve it?



Some context



parentPkg is a function that interacts with a web application, takes some request and data and returns results from different statistical models depending on the scenarios.

Each scenario is quite complex and not everything can be generalised in parentPkg. For this reason, childPkg1 and childPkg2 (actually there are also 3 and 4) are sort of sub-packages that deals with the data cleaning and various alternatives for each scenario but return the same class of value.

The idea is that parentPkg would switch the package to the pertinent child depending on the scenario and call all of the necessary functions without having to write the same sequence for each child but just with a slightly different :: call.










share|improve this question






















  • I think if(requireNamespace('childPkg1')) is what you really want
    – MichaelChirico
    4 hours ago














8












8








8







I would like to be able in a call bar::foo(), to be able to programmatically switch the package bar so that the same syntax calls hello::foo().



An example:




  • Let's say I have three packages, parentPkg, childPkg1 and childPkg2.

  • In parentPkg I have a call to function childPkg1::foo()


  • foo() is also a function in childPkg2


  • I would like to be able, in parentPkg to use the :: operator to call foo() but to programatically switch the package name.
    Something like:



    dummy_pkg_name = ifelse(scenario=="child1", "childPkg1", "childPkg2")
    dummy_pkg_name::foo()



Is it possible? How do I achieve it?



Some context



parentPkg is a function that interacts with a web application, takes some request and data and returns results from different statistical models depending on the scenarios.

Each scenario is quite complex and not everything can be generalised in parentPkg. For this reason, childPkg1 and childPkg2 (actually there are also 3 and 4) are sort of sub-packages that deals with the data cleaning and various alternatives for each scenario but return the same class of value.

The idea is that parentPkg would switch the package to the pertinent child depending on the scenario and call all of the necessary functions without having to write the same sequence for each child but just with a slightly different :: call.










share|improve this question













I would like to be able in a call bar::foo(), to be able to programmatically switch the package bar so that the same syntax calls hello::foo().



An example:




  • Let's say I have three packages, parentPkg, childPkg1 and childPkg2.

  • In parentPkg I have a call to function childPkg1::foo()


  • foo() is also a function in childPkg2


  • I would like to be able, in parentPkg to use the :: operator to call foo() but to programatically switch the package name.
    Something like:



    dummy_pkg_name = ifelse(scenario=="child1", "childPkg1", "childPkg2")
    dummy_pkg_name::foo()



Is it possible? How do I achieve it?



Some context



parentPkg is a function that interacts with a web application, takes some request and data and returns results from different statistical models depending on the scenarios.

Each scenario is quite complex and not everything can be generalised in parentPkg. For this reason, childPkg1 and childPkg2 (actually there are also 3 and 4) are sort of sub-packages that deals with the data cleaning and various alternatives for each scenario but return the same class of value.

The idea is that parentPkg would switch the package to the pertinent child depending on the scenario and call all of the necessary functions without having to write the same sequence for each child but just with a slightly different :: call.







r package






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 4 hours ago









Duccio A

402312




402312












  • I think if(requireNamespace('childPkg1')) is what you really want
    – MichaelChirico
    4 hours ago


















  • I think if(requireNamespace('childPkg1')) is what you really want
    – MichaelChirico
    4 hours ago
















I think if(requireNamespace('childPkg1')) is what you really want
– MichaelChirico
4 hours ago




I think if(requireNamespace('childPkg1')) is what you really want
– MichaelChirico
4 hours ago












3 Answers
3






active

oldest

votes


















9














Since :: can be seen as a function, it looks like



`::`(dummy_pkg_name, foo)()


is what you want. Alternatively,



getFromNamespace("foo", ns = dummy_pkg_name)()




For instance,



`::`(stats, t.test)
# function (x, ...)
# UseMethod("t.test")
# <bytecode: 0x102fd4b00>
# <environment: namespace:stats>

getFromNamespace("t.test", ns = "stats")
# function (x, ...)
# UseMethod("t.test")
# <bytecode: 0x102fd4b00>
# <environment: namespace:stats>





share|improve this answer































    2














    You could also create a call() that could then be evaluated.



    call("::", quote(bar), quote(foo()))
    # bar::foo()


    Put into use:



    c <- call("::", quote(stats), quote(t.test))
    eval(c)
    # function (x, ...)
    # UseMethod("t.test")
    # <bytecode: 0x4340988>
    # <environment: namespace:stats>


    Wrapped up in a function:



    f <- function(pkg, fn) {
    pkg <- substitute(pkg)
    fn <- substitute(fn)
    eval(call("::", pkg, fn))
    }

    f(base, setdiff)
    # function (x, y)
    # {
    # x <- as.vector(x)
    # y <- as.vector(y)
    # unique(if (length(x) || length(y))
    # x[match(x, y, 0L) == 0L]
    # else x)
    # }
    # <bytecode: 0x30f1ea8>
    # <environment: namespace:base>

    f(dplyr, setdiff)
    # function (x, y, ...)
    # UseMethod("setdiff")
    # <environment: namespace:dplyr>





    share|improve this answer































      1














      To adhere to KISS, simply re-assign to new named functions in global environment. Be sure to leave out () since you are not requesting to run the function.



      parent_foo <- parentPkg::foo
      child1_foo <- childPkg1::foo
      child2_foo <- childPkg2::foo
      child3_foo <- childPkg3::foo


      Then, conditionally apply them as needed:



      if (scenario=="child1") {
      obj <- child1_foo(...)
      }
      else if (scenario=="child2") {
      obj <- child2_foo(...)
      }
      ...





      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53978610%2fprogrammatically-switch-package-in-call-in-r%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        9














        Since :: can be seen as a function, it looks like



        `::`(dummy_pkg_name, foo)()


        is what you want. Alternatively,



        getFromNamespace("foo", ns = dummy_pkg_name)()




        For instance,



        `::`(stats, t.test)
        # function (x, ...)
        # UseMethod("t.test")
        # <bytecode: 0x102fd4b00>
        # <environment: namespace:stats>

        getFromNamespace("t.test", ns = "stats")
        # function (x, ...)
        # UseMethod("t.test")
        # <bytecode: 0x102fd4b00>
        # <environment: namespace:stats>





        share|improve this answer




























          9














          Since :: can be seen as a function, it looks like



          `::`(dummy_pkg_name, foo)()


          is what you want. Alternatively,



          getFromNamespace("foo", ns = dummy_pkg_name)()




          For instance,



          `::`(stats, t.test)
          # function (x, ...)
          # UseMethod("t.test")
          # <bytecode: 0x102fd4b00>
          # <environment: namespace:stats>

          getFromNamespace("t.test", ns = "stats")
          # function (x, ...)
          # UseMethod("t.test")
          # <bytecode: 0x102fd4b00>
          # <environment: namespace:stats>





          share|improve this answer


























            9












            9








            9






            Since :: can be seen as a function, it looks like



            `::`(dummy_pkg_name, foo)()


            is what you want. Alternatively,



            getFromNamespace("foo", ns = dummy_pkg_name)()




            For instance,



            `::`(stats, t.test)
            # function (x, ...)
            # UseMethod("t.test")
            # <bytecode: 0x102fd4b00>
            # <environment: namespace:stats>

            getFromNamespace("t.test", ns = "stats")
            # function (x, ...)
            # UseMethod("t.test")
            # <bytecode: 0x102fd4b00>
            # <environment: namespace:stats>





            share|improve this answer














            Since :: can be seen as a function, it looks like



            `::`(dummy_pkg_name, foo)()


            is what you want. Alternatively,



            getFromNamespace("foo", ns = dummy_pkg_name)()




            For instance,



            `::`(stats, t.test)
            # function (x, ...)
            # UseMethod("t.test")
            # <bytecode: 0x102fd4b00>
            # <environment: namespace:stats>

            getFromNamespace("t.test", ns = "stats")
            # function (x, ...)
            # UseMethod("t.test")
            # <bytecode: 0x102fd4b00>
            # <environment: namespace:stats>






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 4 hours ago

























            answered 4 hours ago









            Julius Vainora

            32k75978




            32k75978

























                2














                You could also create a call() that could then be evaluated.



                call("::", quote(bar), quote(foo()))
                # bar::foo()


                Put into use:



                c <- call("::", quote(stats), quote(t.test))
                eval(c)
                # function (x, ...)
                # UseMethod("t.test")
                # <bytecode: 0x4340988>
                # <environment: namespace:stats>


                Wrapped up in a function:



                f <- function(pkg, fn) {
                pkg <- substitute(pkg)
                fn <- substitute(fn)
                eval(call("::", pkg, fn))
                }

                f(base, setdiff)
                # function (x, y)
                # {
                # x <- as.vector(x)
                # y <- as.vector(y)
                # unique(if (length(x) || length(y))
                # x[match(x, y, 0L) == 0L]
                # else x)
                # }
                # <bytecode: 0x30f1ea8>
                # <environment: namespace:base>

                f(dplyr, setdiff)
                # function (x, y, ...)
                # UseMethod("setdiff")
                # <environment: namespace:dplyr>





                share|improve this answer




























                  2














                  You could also create a call() that could then be evaluated.



                  call("::", quote(bar), quote(foo()))
                  # bar::foo()


                  Put into use:



                  c <- call("::", quote(stats), quote(t.test))
                  eval(c)
                  # function (x, ...)
                  # UseMethod("t.test")
                  # <bytecode: 0x4340988>
                  # <environment: namespace:stats>


                  Wrapped up in a function:



                  f <- function(pkg, fn) {
                  pkg <- substitute(pkg)
                  fn <- substitute(fn)
                  eval(call("::", pkg, fn))
                  }

                  f(base, setdiff)
                  # function (x, y)
                  # {
                  # x <- as.vector(x)
                  # y <- as.vector(y)
                  # unique(if (length(x) || length(y))
                  # x[match(x, y, 0L) == 0L]
                  # else x)
                  # }
                  # <bytecode: 0x30f1ea8>
                  # <environment: namespace:base>

                  f(dplyr, setdiff)
                  # function (x, y, ...)
                  # UseMethod("setdiff")
                  # <environment: namespace:dplyr>





                  share|improve this answer


























                    2












                    2








                    2






                    You could also create a call() that could then be evaluated.



                    call("::", quote(bar), quote(foo()))
                    # bar::foo()


                    Put into use:



                    c <- call("::", quote(stats), quote(t.test))
                    eval(c)
                    # function (x, ...)
                    # UseMethod("t.test")
                    # <bytecode: 0x4340988>
                    # <environment: namespace:stats>


                    Wrapped up in a function:



                    f <- function(pkg, fn) {
                    pkg <- substitute(pkg)
                    fn <- substitute(fn)
                    eval(call("::", pkg, fn))
                    }

                    f(base, setdiff)
                    # function (x, y)
                    # {
                    # x <- as.vector(x)
                    # y <- as.vector(y)
                    # unique(if (length(x) || length(y))
                    # x[match(x, y, 0L) == 0L]
                    # else x)
                    # }
                    # <bytecode: 0x30f1ea8>
                    # <environment: namespace:base>

                    f(dplyr, setdiff)
                    # function (x, y, ...)
                    # UseMethod("setdiff")
                    # <environment: namespace:dplyr>





                    share|improve this answer














                    You could also create a call() that could then be evaluated.



                    call("::", quote(bar), quote(foo()))
                    # bar::foo()


                    Put into use:



                    c <- call("::", quote(stats), quote(t.test))
                    eval(c)
                    # function (x, ...)
                    # UseMethod("t.test")
                    # <bytecode: 0x4340988>
                    # <environment: namespace:stats>


                    Wrapped up in a function:



                    f <- function(pkg, fn) {
                    pkg <- substitute(pkg)
                    fn <- substitute(fn)
                    eval(call("::", pkg, fn))
                    }

                    f(base, setdiff)
                    # function (x, y)
                    # {
                    # x <- as.vector(x)
                    # y <- as.vector(y)
                    # unique(if (length(x) || length(y))
                    # x[match(x, y, 0L) == 0L]
                    # else x)
                    # }
                    # <bytecode: 0x30f1ea8>
                    # <environment: namespace:base>

                    f(dplyr, setdiff)
                    # function (x, y, ...)
                    # UseMethod("setdiff")
                    # <environment: namespace:dplyr>






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 3 hours ago

























                    answered 3 hours ago









                    Rich Scriven

                    75.7k899168




                    75.7k899168























                        1














                        To adhere to KISS, simply re-assign to new named functions in global environment. Be sure to leave out () since you are not requesting to run the function.



                        parent_foo <- parentPkg::foo
                        child1_foo <- childPkg1::foo
                        child2_foo <- childPkg2::foo
                        child3_foo <- childPkg3::foo


                        Then, conditionally apply them as needed:



                        if (scenario=="child1") {
                        obj <- child1_foo(...)
                        }
                        else if (scenario=="child2") {
                        obj <- child2_foo(...)
                        }
                        ...





                        share|improve this answer


























                          1














                          To adhere to KISS, simply re-assign to new named functions in global environment. Be sure to leave out () since you are not requesting to run the function.



                          parent_foo <- parentPkg::foo
                          child1_foo <- childPkg1::foo
                          child2_foo <- childPkg2::foo
                          child3_foo <- childPkg3::foo


                          Then, conditionally apply them as needed:



                          if (scenario=="child1") {
                          obj <- child1_foo(...)
                          }
                          else if (scenario=="child2") {
                          obj <- child2_foo(...)
                          }
                          ...





                          share|improve this answer
























                            1












                            1








                            1






                            To adhere to KISS, simply re-assign to new named functions in global environment. Be sure to leave out () since you are not requesting to run the function.



                            parent_foo <- parentPkg::foo
                            child1_foo <- childPkg1::foo
                            child2_foo <- childPkg2::foo
                            child3_foo <- childPkg3::foo


                            Then, conditionally apply them as needed:



                            if (scenario=="child1") {
                            obj <- child1_foo(...)
                            }
                            else if (scenario=="child2") {
                            obj <- child2_foo(...)
                            }
                            ...





                            share|improve this answer












                            To adhere to KISS, simply re-assign to new named functions in global environment. Be sure to leave out () since you are not requesting to run the function.



                            parent_foo <- parentPkg::foo
                            child1_foo <- childPkg1::foo
                            child2_foo <- childPkg2::foo
                            child3_foo <- childPkg3::foo


                            Then, conditionally apply them as needed:



                            if (scenario=="child1") {
                            obj <- child1_foo(...)
                            }
                            else if (scenario=="child2") {
                            obj <- child2_foo(...)
                            }
                            ...






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 1 hour ago









                            Parfait

                            49.6k84168




                            49.6k84168






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53978610%2fprogrammatically-switch-package-in-call-in-r%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Scott Moir

                                Souastre

                                Morgemoulin