【问题标题】:Declare a variable within a function to be used outside the function (but not declare globally)在函数内声明要在函数外使用的变量(但不全局声明)
【发布时间】:2019-05-09 09:15:11
【问题描述】:

如果您想在函数g 中声明一个新变量,我知道您可以使用<<- 将其声明为全局变量。

g=function(t){
 a<<-t
}
g(0)
print(a)
#It gives "0"

如果函数 g 已经在另一个函数 f 中,并且您希望函数 g 在函数 f 中声明一个新变量但不是全局变量,该怎么办?

g=function(t){
   #declare the variable a and assign it the value t   
 }
f=function(t){
   g(t)
   return(a)
}
f(0)
#It should give 0.
print(a)
#It should say that the variable a is unknown.

【问题讨论】:

  • 来自 g 函数,它声明了一个
  • a &lt;- g(t);return(a) 是一个选项吗?

标签: r function variables


【解决方案1】:

f 中嵌套g 并确保初始化a

f = function(t){
  g = function(t){
    a <<- t
  }
  a <- NULL
  g(t)
  return(a)
}

f(0)
## [1] 0

如果不想在f 中定义g,可以动态插入:

g = function(t){
  a <<- t
}

f = function(t){
  environment(g) <- environment()
  a <- NULL
  g(t)
  return(a)
}

f(0)
## [1] 0

上述任何示例中a &lt;&lt;- t 的替代方案如下。它们不需要初始化a

parent.frame()$a <- t

assign("a", t, parent.frame())

例如,

g = function(t, envir = parent.frame()) {
  envir$a <- t
}

f = function(t) {
  g(t)
  return(a)
}

f(0)
## [1] 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2011-10-11
    • 2012-09-01
    相关资源
    最近更新 更多