W7GVR
W7GVR

Reputation: 2000

in R: how to get result of an operation evaluated in specified environment

In R, suppose you have an environment "big.env" containing a large data frame "big.df" and you want to retrieve a small subset from "big.df".

You could do the following in the interactive/global enviroment:

  big.df = get("big.df", envir = big.env)
  my.subset = subset(big.df, my.index.table==desired.subset.value)

Is there a way to do the sub-setting AND the retrieval from "big.env" in a single step?

My failed attempts are shown below:

  my.subset = eval("subset(big.df, my.index.table==desired.subset.value)", envir = big.env)
  my.subset = eval(as.expression("subset(big.df, my.index.table==desired.subset.value))", envir = big.env)
  my.subset = eval(expression("subset(big.df, my.index.table==desired.subset.value))", envir = big.env)

More generally, is there a way to execute an instruction within an environment and get the result into the current/global environment? For instance, get the colnames of big.df in example above by something like:

  my.colnames = eval(as.expression("colnames(big.df)", envir = big.env)

Upvotes: 1

Views: 30

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269556

1) Refer to it as big.env$big.df . For example, using the built-in six row data frame, BOD we create a test environment e containing twice BOD and then extract the rows whose Time values are greater than the mean Time:

e <- local({ BOD2 <- 2 * BOD; environment() }) # test data

subset(e$BOD2, Time > mean(Time))

giving:

  Time demand
4    8   32.0
5   10   31.2
6   14   39.6

2) with is another approach:

with(e, subset(BOD2, Time > mean(Time)))

or

subset(with(e, BOD2), Time > mean(Time))

Upvotes: 1

Related Questions