Search code examples
rfunctionscopingrprofile

Accessing function's parent environment and removing objects


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.


Solution

  • 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