Dmitriy
Dmitriy

Reputation: 939

Environment expansion in R

I have some problem I don't know how to solve. Prehistory: I use R.NET for my calculation (need WPF application). So, I want to parallelize my app, and I created dynamic proxy for REngine class. It needs to serialize data to pass and receive data from-to REngine instance via TCP. Bad news - R.NET classes cannot be serialized. So, I have an idea to serialize R objects in R and pass R serialized data between processes.

So I have same script like this:

a <- 5;
b <- 10;
x <- a+b;

I need to wrap it like this:

wrapFunction <- function()
{
    a <- 5;
    b <- 10;
    x <- a+b;
}

serializedResult <- serialize(wrapFunction());

I'll get serializedResult and pass it as byte array. Also I need to pass environments. But I won't get a, b, x in .GlobalEnv after these manipulations. How is it possible to get all variables, defined in function body, in my .GlobalEnv? I don't know names and count, I can't rewrite basic script, replacing "<-" by "<<-". Other ways?

Thank you.

Upvotes: 2

Views: 83

Answers (1)

Roland
Roland

Reputation: 132706

I'm not sure I fully understand your requirements. They seem to go against the functional language paradigm, which R tries to follow. The following might be helpful or not:

e <- new.env()
wrapFunction <- function(){
  with(e, {
         a <- 5;
         b <- 10;
         x <- a+b;
          })
}

wrapFunction()
e$a
#[1] 5

You can of course use the .GlobalEnv instead of e, but at least in R that would be considered an even worse practice.

Upvotes: 1

Related Questions