4

假设我想编写一个简单的重命名函数,该函数将通过.Rprofile. 函数很简单,可以类比:

carsNewName <- mtcars; rm(mtcars)

.Rprofile

可用的函数.Rprofile格式为:

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

在哪里。env通过 连接attach(.env)

问题

如何通过 访问函数的父环境parent.env()即如果rename函数在另一个函数中被调用,我想在全局环境中重命名对象。

4

1 回答 1

6

f从父环境显示x,然后x从父框架显示:

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()

给予:

[1] 0
[1] 1
于 2016-10-22T11:17:46.593 回答