LAP
LAP

Reputation: 6685

Can I save the temporary environment of a function in R?

I'm currently writing a rather large function for a specific plot. I would like to keep all the objects created by the function for bugfixing reasons, but my web search so far has been unsuccessful.

A quick visualization. Suppose

fun <- function(x) {
  y <- x+1
  z <- y^2
  z*4
}

fun(2)
[1] 36

For this simple case, I would like to keep y and z in an accessible environment to be able to comprehend which results certain stages of my function produce.

Thanks in advance!

Upvotes: 0

Views: 1479

Answers (2)

Kalin
Kalin

Reputation: 1761

Similar to the answer from @user116, there is a special operator for achieving what you want.

It's a shortcut to the assignment function using the <<- operator. Check out help("<<-") for more info. But basically, you could "save" y and z in the global environment by doing this:

# Make sure that these do not exist first.
stopifnot( all( !exists("y"), !exists("z")))

fun <- function(x) {
  y <<- x+1
  z <<- y^2
  z*4
}

fun(2)

# Verify y and z exist now.
stopifnot( all( exists("y"), exists("z")))
y
z

There's a lot to learn about environments, which might be helpful for writing long functions, etc., so this is just the tip of the iceberg.

Upvotes: 2

user116
user116

Reputation: 88

You could return the objects in a list or assign the variables inside the function with

assign("x", x, envir = .GlobalEnv)

Upvotes: 2

Related Questions