How to avoid reading data from R environment within Rcpp functionHow to join (merge) data frames (inner, outer, left, right)Read variables from global environment with inline Rcpp?Evaluate expressions in environments in Rcpprcpp function calling another rcpp functionAvoiding copies by using environmentsRcpp: Call C function from a package within Rcpprcpp updating data in base environmentEnvironments in R functions and RcppCall a function from c++ via environment Rcppparallel::clusterExport how to pass nested functions from global environment?

How to model explosives?

Why are electrically insulating heatsinks so rare? Is it just cost?

Blender 2.8 I can't see vertices, edges or faces in edit mode

Intersection of two sorted vectors in C++

Has there ever been an airliner design involving reducing generator load by installing solar panels?

What exploit are these user agents trying to use?

Can one be a co-translator of a book, if he does not know the language that the book is translated into?

How do I write bicross product symbols in latex?

How to prevent "they're falling in love" trope

Is it canonical bit space?

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?

Why doesn't H₄O²⁺ exist?

Emailing HOD to enhance faculty application

SSH "lag" in LAN on some machines, mixed distros

How much of data wrangling is a data scientist's job?

Should I tell management that I intend to leave due to bad software development practices?

Can I use a neutral wire from another outlet to repair a broken neutral?

Why is the 'in' operator throwing an error with a string literal instead of logging false?

Why does Arabsat 6A need a Falcon Heavy to launch

What mechanic is there to disable a threat instead of killing it?

Today is the Center

Do I have a twin with permutated remainders?

Fully-Firstable Anagram Sets

Is it unprofessional to ask if a job posting on GlassDoor is real?



How to avoid reading data from R environment within Rcpp function


How to join (merge) data frames (inner, outer, left, right)Read variables from global environment with inline Rcpp?Evaluate expressions in environments in Rcpprcpp function calling another rcpp functionAvoiding copies by using environmentsRcpp: Call C function from a package within Rcpprcpp updating data in base environmentEnvironments in R functions and RcppCall a function from c++ via environment Rcppparallel::clusterExport how to pass nested functions from global environment?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















Even though MyCppFunction(NumericVector x) returns the desired output, I am not sure of a proper/efficient way to avoid reading the data on variable myY withou passing it as a function argument.



The reason I do not pass the data as an argument is that I will eventually pass the C++ function as an objective function to minimize and the minimization routine accepts a function of one argument only, namely myX. Just as an example: in R, I would pass myY to optim(...) in the following way : optim(par,fn=MyRFunction,y=myY).



Any advice on how to properly access myY from within the C++ function is appreciated, here's a minimal example of what I am afraid is a really wrong way to do it:



Update : I've modified the code to better reflect the context as well as what has been proposed in the answers. Just in case, the focus of my question lies on this line : NumericVector y = env["myY"]; // How to avoid this?



#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double MyCppFunction(NumericVector x)

Environment env = Environment::global_env();
NumericVector y = env["myY"]; // How to avoid this?

double res = 0;

for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

return res;


double MyCppFunctionNoExport(NumericVector x)

Environment env = Environment::global_env();
NumericVector y = env["myY"]; // How to avoid this?

double res = 0;

for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

return res;


// [[Rcpp::export]]
double MyCppFunction2(NumericVector x, NumericVector y)
double res = 0;

for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

return res;


// [[Rcpp::export]]
double MyRoutine(NumericVector x, Function fn)

for (int i = 0; i < x.size(); i++) fn(x);

return 0;


// [[Rcpp::export]]
double MyRoutineNoExport(NumericVector x)

for (int i = 0; i < x.size(); i++) MyCppFunctionNoExport(x);

return 0;


/*** R
MyRFunction <- function(x, y=myY)
res = 0
for(i in 1:length(x)) res = res + (x[i]*y[i])
return (res)


callMyCppFunction2 <- function(x)
MyCppFunction2(x, myY)


set.seed(123456)

myY = rnorm(1e3)
myX = rnorm(1e3)

all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX))

require(rbenchmark)

benchmark(MyRoutine(myX, fn=MyCppFunction),
MyRoutine(myX, fn=MyRFunction),
MyRoutine(myX, fn=callMyCppFunction2),
MyRoutineNoExport(myX), order="relative")[, 1:4]

*/


Output:




$ Rscript -e 'Rcpp::sourceCpp("stack.cpp")'
> MyRFunction <- function(x, y = myY)
+ res = 0
+ for (i in 1:length(x)) res = res + (x[i] * y[i])
+ return(res)
+

> callMyCppFunction2 <- function(x)
+ MyCppFunction2(x, myY)
+

> set.seed(123456)

> myY = rnorm(1000)

> myX = rnorm(1000)

> all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX))
[1] TRUE

> require(rbenchmark)
Loading required package: rbenchmark

> benchmark(MyRoutine(myX, fn = MyCppFunction), MyRoutine(myX,
+ fn = MyRFunction), MyRoutine(myX, fn = callMyCppFunction2),
+ MyRoutineNoEx .... [TRUNCATED]
test replications elapsed relative
4 MyRoutineNoExport(myX) 100 1.692 1.000
1 MyRoutine(myX, fn = MyCppFunction) 100 3.047 1.801
3 MyRoutine(myX, fn = callMyCppFunction2) 100 3.454 2.041
2 MyRoutine(myX, fn = MyRFunction) 100 8.277 4.892










share|improve this question






























    1















    Even though MyCppFunction(NumericVector x) returns the desired output, I am not sure of a proper/efficient way to avoid reading the data on variable myY withou passing it as a function argument.



    The reason I do not pass the data as an argument is that I will eventually pass the C++ function as an objective function to minimize and the minimization routine accepts a function of one argument only, namely myX. Just as an example: in R, I would pass myY to optim(...) in the following way : optim(par,fn=MyRFunction,y=myY).



    Any advice on how to properly access myY from within the C++ function is appreciated, here's a minimal example of what I am afraid is a really wrong way to do it:



    Update : I've modified the code to better reflect the context as well as what has been proposed in the answers. Just in case, the focus of my question lies on this line : NumericVector y = env["myY"]; // How to avoid this?



    #include <Rcpp.h>
    using namespace Rcpp;

    // [[Rcpp::export]]
    double MyCppFunction(NumericVector x)

    Environment env = Environment::global_env();
    NumericVector y = env["myY"]; // How to avoid this?

    double res = 0;

    for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

    return res;


    double MyCppFunctionNoExport(NumericVector x)

    Environment env = Environment::global_env();
    NumericVector y = env["myY"]; // How to avoid this?

    double res = 0;

    for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

    return res;


    // [[Rcpp::export]]
    double MyCppFunction2(NumericVector x, NumericVector y)
    double res = 0;

    for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

    return res;


    // [[Rcpp::export]]
    double MyRoutine(NumericVector x, Function fn)

    for (int i = 0; i < x.size(); i++) fn(x);

    return 0;


    // [[Rcpp::export]]
    double MyRoutineNoExport(NumericVector x)

    for (int i = 0; i < x.size(); i++) MyCppFunctionNoExport(x);

    return 0;


    /*** R
    MyRFunction <- function(x, y=myY)
    res = 0
    for(i in 1:length(x)) res = res + (x[i]*y[i])
    return (res)


    callMyCppFunction2 <- function(x)
    MyCppFunction2(x, myY)


    set.seed(123456)

    myY = rnorm(1e3)
    myX = rnorm(1e3)

    all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX))

    require(rbenchmark)

    benchmark(MyRoutine(myX, fn=MyCppFunction),
    MyRoutine(myX, fn=MyRFunction),
    MyRoutine(myX, fn=callMyCppFunction2),
    MyRoutineNoExport(myX), order="relative")[, 1:4]

    */


    Output:




    $ Rscript -e 'Rcpp::sourceCpp("stack.cpp")'
    > MyRFunction <- function(x, y = myY)
    + res = 0
    + for (i in 1:length(x)) res = res + (x[i] * y[i])
    + return(res)
    +

    > callMyCppFunction2 <- function(x)
    + MyCppFunction2(x, myY)
    +

    > set.seed(123456)

    > myY = rnorm(1000)

    > myX = rnorm(1000)

    > all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX))
    [1] TRUE

    > require(rbenchmark)
    Loading required package: rbenchmark

    > benchmark(MyRoutine(myX, fn = MyCppFunction), MyRoutine(myX,
    + fn = MyRFunction), MyRoutine(myX, fn = callMyCppFunction2),
    + MyRoutineNoEx .... [TRUNCATED]
    test replications elapsed relative
    4 MyRoutineNoExport(myX) 100 1.692 1.000
    1 MyRoutine(myX, fn = MyCppFunction) 100 3.047 1.801
    3 MyRoutine(myX, fn = callMyCppFunction2) 100 3.454 2.041
    2 MyRoutine(myX, fn = MyRFunction) 100 8.277 4.892










    share|improve this question


























      1












      1








      1








      Even though MyCppFunction(NumericVector x) returns the desired output, I am not sure of a proper/efficient way to avoid reading the data on variable myY withou passing it as a function argument.



      The reason I do not pass the data as an argument is that I will eventually pass the C++ function as an objective function to minimize and the minimization routine accepts a function of one argument only, namely myX. Just as an example: in R, I would pass myY to optim(...) in the following way : optim(par,fn=MyRFunction,y=myY).



      Any advice on how to properly access myY from within the C++ function is appreciated, here's a minimal example of what I am afraid is a really wrong way to do it:



      Update : I've modified the code to better reflect the context as well as what has been proposed in the answers. Just in case, the focus of my question lies on this line : NumericVector y = env["myY"]; // How to avoid this?



      #include <Rcpp.h>
      using namespace Rcpp;

      // [[Rcpp::export]]
      double MyCppFunction(NumericVector x)

      Environment env = Environment::global_env();
      NumericVector y = env["myY"]; // How to avoid this?

      double res = 0;

      for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

      return res;


      double MyCppFunctionNoExport(NumericVector x)

      Environment env = Environment::global_env();
      NumericVector y = env["myY"]; // How to avoid this?

      double res = 0;

      for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

      return res;


      // [[Rcpp::export]]
      double MyCppFunction2(NumericVector x, NumericVector y)
      double res = 0;

      for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

      return res;


      // [[Rcpp::export]]
      double MyRoutine(NumericVector x, Function fn)

      for (int i = 0; i < x.size(); i++) fn(x);

      return 0;


      // [[Rcpp::export]]
      double MyRoutineNoExport(NumericVector x)

      for (int i = 0; i < x.size(); i++) MyCppFunctionNoExport(x);

      return 0;


      /*** R
      MyRFunction <- function(x, y=myY)
      res = 0
      for(i in 1:length(x)) res = res + (x[i]*y[i])
      return (res)


      callMyCppFunction2 <- function(x)
      MyCppFunction2(x, myY)


      set.seed(123456)

      myY = rnorm(1e3)
      myX = rnorm(1e3)

      all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX))

      require(rbenchmark)

      benchmark(MyRoutine(myX, fn=MyCppFunction),
      MyRoutine(myX, fn=MyRFunction),
      MyRoutine(myX, fn=callMyCppFunction2),
      MyRoutineNoExport(myX), order="relative")[, 1:4]

      */


      Output:




      $ Rscript -e 'Rcpp::sourceCpp("stack.cpp")'
      > MyRFunction <- function(x, y = myY)
      + res = 0
      + for (i in 1:length(x)) res = res + (x[i] * y[i])
      + return(res)
      +

      > callMyCppFunction2 <- function(x)
      + MyCppFunction2(x, myY)
      +

      > set.seed(123456)

      > myY = rnorm(1000)

      > myX = rnorm(1000)

      > all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX))
      [1] TRUE

      > require(rbenchmark)
      Loading required package: rbenchmark

      > benchmark(MyRoutine(myX, fn = MyCppFunction), MyRoutine(myX,
      + fn = MyRFunction), MyRoutine(myX, fn = callMyCppFunction2),
      + MyRoutineNoEx .... [TRUNCATED]
      test replications elapsed relative
      4 MyRoutineNoExport(myX) 100 1.692 1.000
      1 MyRoutine(myX, fn = MyCppFunction) 100 3.047 1.801
      3 MyRoutine(myX, fn = callMyCppFunction2) 100 3.454 2.041
      2 MyRoutine(myX, fn = MyRFunction) 100 8.277 4.892










      share|improve this question
















      Even though MyCppFunction(NumericVector x) returns the desired output, I am not sure of a proper/efficient way to avoid reading the data on variable myY withou passing it as a function argument.



      The reason I do not pass the data as an argument is that I will eventually pass the C++ function as an objective function to minimize and the minimization routine accepts a function of one argument only, namely myX. Just as an example: in R, I would pass myY to optim(...) in the following way : optim(par,fn=MyRFunction,y=myY).



      Any advice on how to properly access myY from within the C++ function is appreciated, here's a minimal example of what I am afraid is a really wrong way to do it:



      Update : I've modified the code to better reflect the context as well as what has been proposed in the answers. Just in case, the focus of my question lies on this line : NumericVector y = env["myY"]; // How to avoid this?



      #include <Rcpp.h>
      using namespace Rcpp;

      // [[Rcpp::export]]
      double MyCppFunction(NumericVector x)

      Environment env = Environment::global_env();
      NumericVector y = env["myY"]; // How to avoid this?

      double res = 0;

      for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

      return res;


      double MyCppFunctionNoExport(NumericVector x)

      Environment env = Environment::global_env();
      NumericVector y = env["myY"]; // How to avoid this?

      double res = 0;

      for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

      return res;


      // [[Rcpp::export]]
      double MyCppFunction2(NumericVector x, NumericVector y)
      double res = 0;

      for (int i = 0; i < x.size(); i++) res = res + (x(i) * y(i));

      return res;


      // [[Rcpp::export]]
      double MyRoutine(NumericVector x, Function fn)

      for (int i = 0; i < x.size(); i++) fn(x);

      return 0;


      // [[Rcpp::export]]
      double MyRoutineNoExport(NumericVector x)

      for (int i = 0; i < x.size(); i++) MyCppFunctionNoExport(x);

      return 0;


      /*** R
      MyRFunction <- function(x, y=myY)
      res = 0
      for(i in 1:length(x)) res = res + (x[i]*y[i])
      return (res)


      callMyCppFunction2 <- function(x)
      MyCppFunction2(x, myY)


      set.seed(123456)

      myY = rnorm(1e3)
      myX = rnorm(1e3)

      all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX))

      require(rbenchmark)

      benchmark(MyRoutine(myX, fn=MyCppFunction),
      MyRoutine(myX, fn=MyRFunction),
      MyRoutine(myX, fn=callMyCppFunction2),
      MyRoutineNoExport(myX), order="relative")[, 1:4]

      */


      Output:




      $ Rscript -e 'Rcpp::sourceCpp("stack.cpp")'
      > MyRFunction <- function(x, y = myY)
      + res = 0
      + for (i in 1:length(x)) res = res + (x[i] * y[i])
      + return(res)
      +

      > callMyCppFunction2 <- function(x)
      + MyCppFunction2(x, myY)
      +

      > set.seed(123456)

      > myY = rnorm(1000)

      > myX = rnorm(1000)

      > all.equal(MyCppFunction(myX), MyRFunction(myX), callMyCppFunction2(myX))
      [1] TRUE

      > require(rbenchmark)
      Loading required package: rbenchmark

      > benchmark(MyRoutine(myX, fn = MyCppFunction), MyRoutine(myX,
      + fn = MyRFunction), MyRoutine(myX, fn = callMyCppFunction2),
      + MyRoutineNoEx .... [TRUNCATED]
      test replications elapsed relative
      4 MyRoutineNoExport(myX) 100 1.692 1.000
      1 MyRoutine(myX, fn = MyCppFunction) 100 3.047 1.801
      3 MyRoutine(myX, fn = callMyCppFunction2) 100 3.454 2.041
      2 MyRoutine(myX, fn = MyRFunction) 100 8.277 4.892







      r optimization rcpp






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 9 at 17:40







      NewUser

















      asked Mar 8 at 23:26









      NewUserNewUser

      1027




      1027






















          3 Answers
          3






          active

          oldest

          votes


















          1














          Another solution. Set global in C space:



          #include <Rcpp.h>
          using namespace Rcpp;

          static NumericVector yglobal;

          // [[Rcpp::export]]
          void set_Y(NumericVector y)
          yglobal = y;


          // [[Rcpp::export]]
          double MyCppFunction(NumericVector x)
          double res = 0;
          for (int i = 0; i < x.size(); i++) res = res + (x(i) * yglobal(i));
          return res;



          R side:



          set.seed(123456)

          myY = rnorm(1000)
          set_Y(myY);
          myX = rnorm(1000)

          MyCppFunction(myX)


          (Note: the purpose of static is to limit the scope of the variable to your particular script)






          share|improve this answer






























            3














            Use two parameters and wrap the C++ function in an R function.



            #include <Rcpp.h>
            using namespace Rcpp;
            // [[Rcpp::export]]
            double MyCppFunction(NumericVector x, NumericVector y)
            return (sum(x) + sum(y));



            R side:



            callMyCFunc <- function(x) 
            MyCppFunction(x, myY)






            share|improve this answer























            • Thanks, I've also tried that. The problem is that the function will be called from a C++ loop and hence wrapping it as an R function ends up being slower than using my original R version.

              – NewUser
              Mar 9 at 16:26











            • I've modified the code and included your answer. However this is on of the solutions I'm trying to avoid...

              – NewUser
              Mar 9 at 17:46


















            2














            optim does allow one to pass additional variables. Here we minimize f over x and pass in the additional variable a.



            f <- function(x, a) sum((x - a)^2)
            optim(1:2, f, a = 1)


            giving:



            $par
            [1] 1.0000030 0.9999351

            $value
            [1] 4.22133e-09

            $counts
            function gradient
            63 NA

            $convergence
            [1] 0

            $message
            NULL





            share|improve this answer




















            • 1





              Thanks, but I am aware of that. I probably shouldn't have mentioned optim. I mentioned it as an example of what I cannot do and what is forcing me to make the Environment::global_env() call inside of the C++ function. I will think of a more concrete example.

              – NewUser
              Mar 9 at 3:00











            • If you really are using a routine that does not accept additional fixed parameters you can curry your function like this: library(purrr); f2 <- partial(f, a = 1); optim(1:2, f2)

              – G. Grothendieck
              Mar 9 at 11:53












            • I've modified the question in case you want to take a look. I'd prefer a base RRcpp solution though.

              – NewUser
              Mar 9 at 17:47











            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%2f55072378%2fhow-to-avoid-reading-data-from-r-environment-within-rcpp-function%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









            1














            Another solution. Set global in C space:



            #include <Rcpp.h>
            using namespace Rcpp;

            static NumericVector yglobal;

            // [[Rcpp::export]]
            void set_Y(NumericVector y)
            yglobal = y;


            // [[Rcpp::export]]
            double MyCppFunction(NumericVector x)
            double res = 0;
            for (int i = 0; i < x.size(); i++) res = res + (x(i) * yglobal(i));
            return res;



            R side:



            set.seed(123456)

            myY = rnorm(1000)
            set_Y(myY);
            myX = rnorm(1000)

            MyCppFunction(myX)


            (Note: the purpose of static is to limit the scope of the variable to your particular script)






            share|improve this answer



























              1














              Another solution. Set global in C space:



              #include <Rcpp.h>
              using namespace Rcpp;

              static NumericVector yglobal;

              // [[Rcpp::export]]
              void set_Y(NumericVector y)
              yglobal = y;


              // [[Rcpp::export]]
              double MyCppFunction(NumericVector x)
              double res = 0;
              for (int i = 0; i < x.size(); i++) res = res + (x(i) * yglobal(i));
              return res;



              R side:



              set.seed(123456)

              myY = rnorm(1000)
              set_Y(myY);
              myX = rnorm(1000)

              MyCppFunction(myX)


              (Note: the purpose of static is to limit the scope of the variable to your particular script)






              share|improve this answer

























                1












                1








                1







                Another solution. Set global in C space:



                #include <Rcpp.h>
                using namespace Rcpp;

                static NumericVector yglobal;

                // [[Rcpp::export]]
                void set_Y(NumericVector y)
                yglobal = y;


                // [[Rcpp::export]]
                double MyCppFunction(NumericVector x)
                double res = 0;
                for (int i = 0; i < x.size(); i++) res = res + (x(i) * yglobal(i));
                return res;



                R side:



                set.seed(123456)

                myY = rnorm(1000)
                set_Y(myY);
                myX = rnorm(1000)

                MyCppFunction(myX)


                (Note: the purpose of static is to limit the scope of the variable to your particular script)






                share|improve this answer













                Another solution. Set global in C space:



                #include <Rcpp.h>
                using namespace Rcpp;

                static NumericVector yglobal;

                // [[Rcpp::export]]
                void set_Y(NumericVector y)
                yglobal = y;


                // [[Rcpp::export]]
                double MyCppFunction(NumericVector x)
                double res = 0;
                for (int i = 0; i < x.size(); i++) res = res + (x(i) * yglobal(i));
                return res;



                R side:



                set.seed(123456)

                myY = rnorm(1000)
                set_Y(myY);
                myX = rnorm(1000)

                MyCppFunction(myX)


                (Note: the purpose of static is to limit the scope of the variable to your particular script)







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 9 at 20:26









                thcthc

                5,42111224




                5,42111224























                    3














                    Use two parameters and wrap the C++ function in an R function.



                    #include <Rcpp.h>
                    using namespace Rcpp;
                    // [[Rcpp::export]]
                    double MyCppFunction(NumericVector x, NumericVector y)
                    return (sum(x) + sum(y));



                    R side:



                    callMyCFunc <- function(x) 
                    MyCppFunction(x, myY)






                    share|improve this answer























                    • Thanks, I've also tried that. The problem is that the function will be called from a C++ loop and hence wrapping it as an R function ends up being slower than using my original R version.

                      – NewUser
                      Mar 9 at 16:26











                    • I've modified the code and included your answer. However this is on of the solutions I'm trying to avoid...

                      – NewUser
                      Mar 9 at 17:46















                    3














                    Use two parameters and wrap the C++ function in an R function.



                    #include <Rcpp.h>
                    using namespace Rcpp;
                    // [[Rcpp::export]]
                    double MyCppFunction(NumericVector x, NumericVector y)
                    return (sum(x) + sum(y));



                    R side:



                    callMyCFunc <- function(x) 
                    MyCppFunction(x, myY)






                    share|improve this answer























                    • Thanks, I've also tried that. The problem is that the function will be called from a C++ loop and hence wrapping it as an R function ends up being slower than using my original R version.

                      – NewUser
                      Mar 9 at 16:26











                    • I've modified the code and included your answer. However this is on of the solutions I'm trying to avoid...

                      – NewUser
                      Mar 9 at 17:46













                    3












                    3








                    3







                    Use two parameters and wrap the C++ function in an R function.



                    #include <Rcpp.h>
                    using namespace Rcpp;
                    // [[Rcpp::export]]
                    double MyCppFunction(NumericVector x, NumericVector y)
                    return (sum(x) + sum(y));



                    R side:



                    callMyCFunc <- function(x) 
                    MyCppFunction(x, myY)






                    share|improve this answer













                    Use two parameters and wrap the C++ function in an R function.



                    #include <Rcpp.h>
                    using namespace Rcpp;
                    // [[Rcpp::export]]
                    double MyCppFunction(NumericVector x, NumericVector y)
                    return (sum(x) + sum(y));



                    R side:



                    callMyCFunc <- function(x) 
                    MyCppFunction(x, myY)







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 9 at 4:06









                    thcthc

                    5,42111224




                    5,42111224












                    • Thanks, I've also tried that. The problem is that the function will be called from a C++ loop and hence wrapping it as an R function ends up being slower than using my original R version.

                      – NewUser
                      Mar 9 at 16:26











                    • I've modified the code and included your answer. However this is on of the solutions I'm trying to avoid...

                      – NewUser
                      Mar 9 at 17:46

















                    • Thanks, I've also tried that. The problem is that the function will be called from a C++ loop and hence wrapping it as an R function ends up being slower than using my original R version.

                      – NewUser
                      Mar 9 at 16:26











                    • I've modified the code and included your answer. However this is on of the solutions I'm trying to avoid...

                      – NewUser
                      Mar 9 at 17:46
















                    Thanks, I've also tried that. The problem is that the function will be called from a C++ loop and hence wrapping it as an R function ends up being slower than using my original R version.

                    – NewUser
                    Mar 9 at 16:26





                    Thanks, I've also tried that. The problem is that the function will be called from a C++ loop and hence wrapping it as an R function ends up being slower than using my original R version.

                    – NewUser
                    Mar 9 at 16:26













                    I've modified the code and included your answer. However this is on of the solutions I'm trying to avoid...

                    – NewUser
                    Mar 9 at 17:46





                    I've modified the code and included your answer. However this is on of the solutions I'm trying to avoid...

                    – NewUser
                    Mar 9 at 17:46











                    2














                    optim does allow one to pass additional variables. Here we minimize f over x and pass in the additional variable a.



                    f <- function(x, a) sum((x - a)^2)
                    optim(1:2, f, a = 1)


                    giving:



                    $par
                    [1] 1.0000030 0.9999351

                    $value
                    [1] 4.22133e-09

                    $counts
                    function gradient
                    63 NA

                    $convergence
                    [1] 0

                    $message
                    NULL





                    share|improve this answer




















                    • 1





                      Thanks, but I am aware of that. I probably shouldn't have mentioned optim. I mentioned it as an example of what I cannot do and what is forcing me to make the Environment::global_env() call inside of the C++ function. I will think of a more concrete example.

                      – NewUser
                      Mar 9 at 3:00











                    • If you really are using a routine that does not accept additional fixed parameters you can curry your function like this: library(purrr); f2 <- partial(f, a = 1); optim(1:2, f2)

                      – G. Grothendieck
                      Mar 9 at 11:53












                    • I've modified the question in case you want to take a look. I'd prefer a base RRcpp solution though.

                      – NewUser
                      Mar 9 at 17:47















                    2














                    optim does allow one to pass additional variables. Here we minimize f over x and pass in the additional variable a.



                    f <- function(x, a) sum((x - a)^2)
                    optim(1:2, f, a = 1)


                    giving:



                    $par
                    [1] 1.0000030 0.9999351

                    $value
                    [1] 4.22133e-09

                    $counts
                    function gradient
                    63 NA

                    $convergence
                    [1] 0

                    $message
                    NULL





                    share|improve this answer




















                    • 1





                      Thanks, but I am aware of that. I probably shouldn't have mentioned optim. I mentioned it as an example of what I cannot do and what is forcing me to make the Environment::global_env() call inside of the C++ function. I will think of a more concrete example.

                      – NewUser
                      Mar 9 at 3:00











                    • If you really are using a routine that does not accept additional fixed parameters you can curry your function like this: library(purrr); f2 <- partial(f, a = 1); optim(1:2, f2)

                      – G. Grothendieck
                      Mar 9 at 11:53












                    • I've modified the question in case you want to take a look. I'd prefer a base RRcpp solution though.

                      – NewUser
                      Mar 9 at 17:47













                    2












                    2








                    2







                    optim does allow one to pass additional variables. Here we minimize f over x and pass in the additional variable a.



                    f <- function(x, a) sum((x - a)^2)
                    optim(1:2, f, a = 1)


                    giving:



                    $par
                    [1] 1.0000030 0.9999351

                    $value
                    [1] 4.22133e-09

                    $counts
                    function gradient
                    63 NA

                    $convergence
                    [1] 0

                    $message
                    NULL





                    share|improve this answer















                    optim does allow one to pass additional variables. Here we minimize f over x and pass in the additional variable a.



                    f <- function(x, a) sum((x - a)^2)
                    optim(1:2, f, a = 1)


                    giving:



                    $par
                    [1] 1.0000030 0.9999351

                    $value
                    [1] 4.22133e-09

                    $counts
                    function gradient
                    63 NA

                    $convergence
                    [1] 0

                    $message
                    NULL






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 8 at 23:55

























                    answered Mar 8 at 23:37









                    G. GrothendieckG. Grothendieck

                    153k11136244




                    153k11136244







                    • 1





                      Thanks, but I am aware of that. I probably shouldn't have mentioned optim. I mentioned it as an example of what I cannot do and what is forcing me to make the Environment::global_env() call inside of the C++ function. I will think of a more concrete example.

                      – NewUser
                      Mar 9 at 3:00











                    • If you really are using a routine that does not accept additional fixed parameters you can curry your function like this: library(purrr); f2 <- partial(f, a = 1); optim(1:2, f2)

                      – G. Grothendieck
                      Mar 9 at 11:53












                    • I've modified the question in case you want to take a look. I'd prefer a base RRcpp solution though.

                      – NewUser
                      Mar 9 at 17:47












                    • 1





                      Thanks, but I am aware of that. I probably shouldn't have mentioned optim. I mentioned it as an example of what I cannot do and what is forcing me to make the Environment::global_env() call inside of the C++ function. I will think of a more concrete example.

                      – NewUser
                      Mar 9 at 3:00











                    • If you really are using a routine that does not accept additional fixed parameters you can curry your function like this: library(purrr); f2 <- partial(f, a = 1); optim(1:2, f2)

                      – G. Grothendieck
                      Mar 9 at 11:53












                    • I've modified the question in case you want to take a look. I'd prefer a base RRcpp solution though.

                      – NewUser
                      Mar 9 at 17:47







                    1




                    1





                    Thanks, but I am aware of that. I probably shouldn't have mentioned optim. I mentioned it as an example of what I cannot do and what is forcing me to make the Environment::global_env() call inside of the C++ function. I will think of a more concrete example.

                    – NewUser
                    Mar 9 at 3:00





                    Thanks, but I am aware of that. I probably shouldn't have mentioned optim. I mentioned it as an example of what I cannot do and what is forcing me to make the Environment::global_env() call inside of the C++ function. I will think of a more concrete example.

                    – NewUser
                    Mar 9 at 3:00













                    If you really are using a routine that does not accept additional fixed parameters you can curry your function like this: library(purrr); f2 <- partial(f, a = 1); optim(1:2, f2)

                    – G. Grothendieck
                    Mar 9 at 11:53






                    If you really are using a routine that does not accept additional fixed parameters you can curry your function like this: library(purrr); f2 <- partial(f, a = 1); optim(1:2, f2)

                    – G. Grothendieck
                    Mar 9 at 11:53














                    I've modified the question in case you want to take a look. I'd prefer a base RRcpp solution though.

                    – NewUser
                    Mar 9 at 17:47





                    I've modified the question in case you want to take a look. I'd prefer a base RRcpp solution though.

                    – NewUser
                    Mar 9 at 17:47

















                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55072378%2fhow-to-avoid-reading-data-from-r-environment-within-rcpp-function%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

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme