4

Let's say that I want to write a simple rename function that would load through .Rprofile. The function is simple and can be compared to:

carsNewName <- mtcars; rm(mtcars)

.Rprofile

The function available in .Rprofile would be of format:

.env$rename <- function(oldName, newName) {
    newName <- oldName
    rm(oldName, envir = parent.env())
    return(newName)
}

where the .env is attached through attach(.env).

Question

How can I access function's parent environment through parent.env()? I.e. if rename function is called inside another function, I would like to rename objects there not in a global environment.

Konrad
  • 17,740
  • 16
  • 106
  • 167

1 Answers1

6

f displays x from the parent environment and then displays x from the parent frame:

f <- function() {

  e <- environment() # current environment
  p <- parent.env(e)
  print(p$x)

  pf <- parent.frame()
  print(pf$x)

}

g <- function() {
  x <- 1
  f()
}

x <- 0
g()

giving:

[1] 0
[1] 1
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341