繁体   English   中英

访问功能的父环境并删除对象

[英]Accessing function's parent environment and removing objects

假设我想编写一个简单的重命名函数,它将加载.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函数,我想在那里重命名对象而不是在全局环境中。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM