Kon*_*rad 4 r function scoping rprofile
假设我想编写一个简单的重命名函数,它可以通过.Rprofile. 该函数很简单,可以比较为:
carsNewName <- mtcars; rm(mtcars)
Run Code Online (Sandbox Code Playgroud)
.Rprofile可用的函数.Rprofile格式为:
.env$rename <- function(oldName, newName) {
newName <- oldName
rm(oldName, envir = parent.env())
return(newName)
}
Run Code Online (Sandbox Code Playgroud)
在哪里。env通过attach(.env).
如何通过 访问函数的父环境parent.env()?即,如果rename在另一个函数内部调用函数,我想重命名不在全局环境中的对象。
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()
Run Code Online (Sandbox Code Playgroud)
giving:
[1] 0
[1] 1
Run Code Online (Sandbox Code Playgroud)