在R中,如何使函数内部的变量可用于此函数内的较低级函数?(with,attach,environment) [英] In R, how to make the variables inside a function available to the lower level function inside this function?(with, attach, environment)

查看:199
本文介绍了在R中,如何使函数内部的变量可用于此函数内的较低级函数?(with,attach,environment)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新2
@G。 Grothendieck发布了两种方法。第二个是改变函数内的函数环境。这解决了我对编码过多的问题。我不知道如果这是一个很好的方法来通过CRAN检查,当我的脚本进入一个包。当我有一些结论时,我会再次更新。



更新



尝试将很多输入参数变量传递给 f2 ,并且不想将函数内的每个变量索引为 env $ c,env $ d, env $ call ,这就是为什么我试图在 f5 和<$ 中使用 c $ c> f6 (修改后的 f2 )。但是,赋值不适用于 {} ,将分配之外,将执行此工作,但在我的实际情况下,我有几个里面分配,其中包含表达式,我不知道如何将它们从中移出函数很容易。



这是一个例子:

  ##在< environment:R_GlobalEnv> 
a< - 1
b< - 2
f1< - function(){
c < - $ 3
d < - 4
f2< ; - function(P){
assign(calls,calls + 1,inherits = TRUE)
print(calls)
return(P + c + d)
}
调用< - 0
v< - vector()
for(i in 1:10){
v [i]< - f2(P = 0)
c< - c + 1
d< - d + 1
}
return(v)
}
f1()

功能 f2 f1 ,当 f2 被调用时,它在环境中查找变量调用c,d 环境(F1)。这是我想要的。



但是,当我想在其他功能中使用 f2 时,我会在Global环境中定义此函数,调用它 f4

  f4<  -  function(P){
assign(calls,calls + 1,inherits = TRUE)
print(calls)
return(P + c + d)
}

这将无法正常工作,因为它会寻找 c,d ,而不是在调用函数的函数内。例如:

  f3<  -  function(){
c< - 3
d < 4
调用< - 0
v< - vector()
for(i in 1:10){
v [i] < - f4(P = 0)# #或用f5替换(P = 0)
c< - c + 1
d< - d + 1
}
return(v)
}
f3()

安全的方式应该是定义调用,c ,d f4 的输入参数中,然后将这些参数传递到 f4 中。然而,在我的情况下,有太多的变量被传递到这个函数 f4 ,这将是更好的,我可以传递它作为一个环境,并告诉 f4 不要在全局环境中查找( environment(f4)),只查看环境 f3 被调用。



我现在解决的方法是使用环境作为列表,并使用函数的

  f5<  -  function(P,liste){
with(liste,{
assign call,call + 1,inherits = TRUE)
print(calls)
return(P + c + d)
}

}
f3< - function(){
c < - 3
d < - 4
调用< - 0
v< - vector()
for我在1:10){
v [i]< - f5(P = 0,as.list(environment()))##或在这里用f5(P = 0)
c < - c + 1
d< - d + 1
}
return(v)
}
f3()
然而,现在 assign(call,call + 1,inherits = TRUE)不因为 assign 不会修改原始对象。变量调用连接到一个优化函数,其中目标函数是 f5 。这就是我使用 assign 而不是通过调用作为输入参数的原因。使用 attach 对我来说也不清楚。这是我的方法来更正分配问题:

  f7< - 函数(P,调用,列表){
##调用< - - call + 1
## browser()
assign(calls,calls + 1,inherits = TRUE,envir = sys.frame(-1))
打印(调用)
与(liste,{
打印(粘贴('列出的envrionment,calls =',调用))
return(P + c + d)
}

}
########
####### ###########
f8 < - function(){
c < - 3
d < - 4
调用< - 0
v< - vector()
for(i in 1:10){
## browser()
## v [i] < - f4(P = 0)# #或者用f5(P = 0)替换
v [i] < - f7(P = 0,calls,liste = as.list(environment())
c < - c + 1
d < - d + 1
}
f7(P = 0,calls,liste = as.list(environment()))
打印(粘贴(' ',call))
return(v)
}
f8()


$ b $我不知道这是怎么做的,我是在右边特别是当通过CRAN检查?任何人都有一些提示?

解决方案

(1)传递呼叫者的环境。父环境和索引进入它。尝试这样:

  f2a<  -  function(P,env = parent.frame()){
env $调用< - env $ call + 1
print(env $ calls)
return(P + env $ c + env $ d)
}

a< - 1
b< - 2
#与f1相同,除了f2,并且调用f2替换为调用f2a
f1a< - function(){
c < - 3
d< - 4
调用< - 0
v< - vector()
for(i in 1:10){
v [i] f2a(P = 0)
c < - c + 1
d < - d + 1
}
return(v)
}
f1a )

(2)重置被调用函数的环境是重置环境 f2b f1b 中如下所示:

  f2b<  - 函数(P){
调用<< - 调用+ 1
打印(调用)
返回(P + c + d)
}

a< - 1
b< - 2
#与f1相同,除了f2已删除,调用f2替换为调用f2b
#和开始标记为##的行是新
f1b< - function(){
environment(f2b)< - environment()##
c< - 3
d< - 4
调用< - 0
v< - vector()
for(i in 1:10){
v [i]< ; - f2b(P = 0)
c < - c + 1
d < - d + 1
}
return(v)
}
f1b()

(3)使用eval.parent(substitute(...) )另一种方法是定义一个类似宏的结构,它将 f2c 的内容有效地插入到 f1c1 。这里 f2c f2b 相同,除了调用< - call + 1 line(no < - 需要)和整个身体在中的包装eval.parent(substitute({ ...})) f1c f1a 相同,除了调用 f2a 被替换为 f2c 的调用。

  f2c<  -  function(P)eval.parent(substitute({
calls< - calls + 1
打印(通话)
返回(P + c + d)
}))

a < - 1
b< - 2
f1c< - function(){
c < - 3
d < - 4
调用< - 0
v< - vector()
for我在1:10){
v [i] < - f2c(P = 0)
c < - c + 1
d < - d + 1
}
return(v)
}
f1c()

(4)defmacro 除了在gtools软件包中使用 defmacro 以定义宏而不是自己来做,这与最后一个解决方案几乎相同。 (另请参阅另一个defmacro版本的Rcmdr包)由于 defmacro 的工作方式,我们还必须通过调用因为它的一个宏而不是一个功能,所以这只是告诉它代替调用,而不是传递调用到一个功能。

 库(gtools)

f2d < - defmacro(P,calls,expr = {
呼叫< - 呼叫+ 1
打印(通话)
返回(P + c + d)
})

a < - 1
b< - 2
f1d< - function(){
c < - 3
d < - 4
调用< - 0
v< vector()
for(i in 1:10){
v [i] < - f2d(P = 0,calls)
c< - c + 1
d< - d + 1
}
return(v)
}
f1d()


Update 2 @G. Grothendieck posted two approaches. The second one is changing the function environment inside a function. This solves my problem of too many coding replicates. I am not sure if this is a good method to pass through the CRAN check when making my scripts into a package. I will update again when I have some conclusions.

Update

I am trying to pass a lot of input argument variables to f2 and do not want to index every variable inside the function as env$c, env$d, env$calls, that is why I tried to use with in f5 and f6(a modified f2). However, assign does not work with with inside the {}, moving assign outside with will do the job but in my real case I have a few assigns inside the with expressions which I do not know how to move them out of the with function easily.

Here is an example:

## In the <environment: R_GlobalEnv>
a <- 1
b <- 2
f1 <- function(){
    c <- 3
d <- 4
f2 <- function(P){
    assign("calls", calls+1, inherits=TRUE)
    print(calls)
    return(P+c+d)
 }
calls <- 0
v <- vector()
for(i in 1:10){
    v[i] <- f2(P=0)
    c <- c+1
    d <- d+1
  }
 return(v)
}
f1()

Function f2 is inside f1, when f2 is called, it looks for variables calls,c,d in the environment environment(f1). This is what I wanted.

However, when I want to use f2 also in the other functions, I will define this function in the Global environment instead, call it f4.

f4 <- function(P){
  assign("calls", calls+1, inherits=TRUE)
  print(calls)
  return(P+c+d)
}

This won't work, because it will look for calls,c,d in the Global environment instead of inside a function where the function is called. For example:

f3 <- function(){
  c <- 3
  d <- 4
  calls <- 0
  v <- vector()
  for(i in 1:10){
    v[i] <- f4(P=0) ## or replace here with f5(P=0)
    c <- c+1
    d <- d+1
  }
  return(v)
}
f3()

The safe way should be define calls,c,d in the input arguments of f4 and then pass these parameters into f4. However, in my case, there are too many variables to be passed into this function f4 and it would be better that I can pass it as an environment and tell f4 do not look in the Global environment(environment(f4)), only look inside the environment when f3 is called.

The way I solve it now is to use the environment as a list and use the with function.

f5 <- function(P,liste){
  with(liste,{
     assign("calls", calls+1, inherits=TRUE)
     print(calls)
     return(P+c+d)
     }
  )
}
f3 <- function(){
  c <- 3
  d <- 4
  calls <- 0
  v <- vector()
  for(i in 1:10){
    v[i] <- f5(P=0,as.list(environment())) ## or replace here with f5(P=0)
    c <- c+1
    d <- d+1
  }
  return(v)
}
f3()

However, now assign("calls", calls+1, inherits=TRUE) does not work as it should be since assign does not modify the original object. The variable calls is connected to an optimization function where the objective function is f5. That is the reason I use assign instead of passing calls as an input arguments. Using attach is also not clear to me. Here is my way to correct the assign issue:

f7 <- function(P,calls,liste){
  ##calls <<- calls+1
  ##browser()
  assign("calls", calls+1, inherits=TRUE,envir = sys.frame(-1))
  print(calls)
  with(liste,{
    print(paste('with the listed envrionment, calls=',calls))
    return(P+c+d)
  }
  )
}
########
##################
f8 <- function(){
  c <- 3
  d <- 4
  calls <- 0
  v <- vector()
  for(i in 1:10){
    ##browser()
    ##v[i] <- f4(P=0) ## or replace here with f5(P=0)
    v[i] <- f7(P=0,calls,liste=as.list(environment()))
    c <- c+1
    d <- d+1
  }
  f7(P=0,calls,liste=as.list(environment()))
  print(paste('final call number',calls))
  return(v)
}
f8()

I am not sure how this should be done in R. Am I on the right direction, especially when passing through the CRAN check? Anyone has some hints on this?

解决方案

(1) Pass caller's environment. You can explicitly pass the parent environment and index into it. Try this:

f2a <- function(P, env = parent.frame()) {
    env$calls <- env$calls + 1
    print(env$calls)
    return(P + env$c + env$d)
}

a <- 1
b <- 2
# same as f1 except f2 removed and call to f2 replaced with call to f2a
f1a <- function(){
    c <- 3
    d <- 4
    calls <- 0
    v <- vector()
    for(i in 1:10){
        v[i] <- f2a(P=0)
        c <- c+1
        d <- d+1
      }
     return(v)
}
f1a()

(2) Reset called function's environment is to reset the environment of f2b in f1b as shown here:

f2b <- function(P) {
    calls <<- calls + 1
    print(calls)
    return(P + c + d)
}

a <- 1
b <- 2
# same as f1 except f2 removed, call to f2 replaced with call to f2b
#  and line marked ## at the beginning is new
f1b <- function(){
    environment(f2b) <- environment() ##
    c <- 3
    d <- 4
    calls <- 0
    v <- vector()
    for(i in 1:10){
        v[i] <- f2b(P=0)
        c <- c+1
        d <- d+1
      }
     return(v)
}
f1b()

(3) Macro using eval.parent(substitute(...)) Yet another approach is to define a macro-like construct which effectively injects the body of f2c inline into f1c1. Here f2c is the same as f2b except for the calls <- calls + 1 line (no <<- needed) and the wrapping of the entire body in eval.parent(substitute({...})). f1c is the same as f1a except the call to f2a is replaced with a call to f2c .

f2c <- function(P) eval.parent(substitute({
    calls <- calls + 1
    print(calls)
    return(P + c + d)
}))

a <- 1
b <- 2
f1c <- function(){
    c <- 3
    d <- 4
    calls <- 0
    v <- vector()
    for(i in 1:10){
        v[i] <- f2c(P=0)
        c <- c+1
        d <- d+1
      }
     return(v)
}
f1c()

(4) defmacro This is almost the same as the the last solution except it uses defmacro in the gtools package to define the macro rather than doing it ourself. (Also see the Rcmdr package for another defmacro version.) Because of the way defmacro works we must also pass calls but since its a macro and not a function this just tells it to substitute calls in and is not the same as passing calls to a function.

library(gtools)

f2d <- defmacro(P, calls, expr = {
    calls <- calls + 1
    print(calls)
    return(P + c + d)
})

a <- 1
b <- 2
f1d <- function(){
    c <- 3
    d <- 4
    calls <- 0
    v <- vector()
    for(i in 1:10){
        v[i] <- f2d(P=0, calls)
        c <- c+1
        d <- d+1
      }
     return(v)
}
f1d()

这篇关于在R中,如何使函数内部的变量可用于此函数内的较低级函数?(with,attach,environment)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆