2

如何在以下代码段中修改 vairable 'loco' 的值:

poco <- function() {

func <- function(x) {
    print(loco)
    loco <- loco+x
}

loco <- 123
func(1)
func(2)
}

此函数给出以下结果:

> poco()
[1] 123
[1] 123
4

4 回答 4

5
poco <- function() {

func <- function(x) {
    print(loco)
    loco <<- loco+x
}

loco <- 123
func(1)
func(2)
}

This <<- operator assigns to the outer scope. (like assign(..., env=...)). However, as mentioned in the comments, this is usually a bad idea. If you'd like to ask a second question expanding on this where you outline your entire problem, I bet there are other, better choices.

The <<- can bit you in the butt if you're not careful. See this wiki article

What was happening in your first function where you loco <- loco + x is that the function looks outside of the scope of func for loco when it finds it it brings in into the local scope of func and assigns to loco in the local scope rather than the poco scope.

Hope that helps!

于 2012-10-09T15:31:53.473 回答
5

R has a stack of environments. So while you are changing a variable within a function with simple <- or = commands, its value will not change in the outer environment.

To do so, you have several options, as illustrated below:

1st Option:

func <- function(x) {
    print(loco)
    # To modify value of "loco" just in the parent environment, but not globally
    loco <<- loco+x
}

2nd (better) Option:

func <- function(x) {
    print(loco)
    # Again modifies the varaible just in the parent environment, not globally
    assign("loco", loco + x, envir = sys.frame(-1))
}

And the 3rd Option:

func <- function(x) {
    print(loco)
    # To modify the value of a global variable "loco"
    assign("loco", loco + x, envir = .GlobalEnv) 
}

then you will have:

loco <- 123
func(1) # 123
func(2) # 124
loco    # 126

Note that by using options 1 and 2, if you have several nested function definitions, you are modifying the value just in the parent function but not globally.

于 2012-10-09T15:32:04.903 回答
3
poco <- function() {

  func <- function(loco,x) {
    print(loco)
    loco <- loco+x
    loco
  }

  loco <- 123
  loco <- func(loco,1)
  loco <- func(loco,2)
  loco
}
loco_final <- poco()
#[1] 123
#[1] 124
loco_final
#[1] 126
于 2012-10-09T15:25:18.077 回答
3

loco一般来说,在功能中没有改变是一件好事。不使用这些全局变量可确保变量不会干扰较大脚本中的每个变量。

假设您blafunction_aand中使用了一个变量function_b。预测函数调用的结果很困难,因为它取决于bla. 用行话来说,这被称为函数有副作用。不使用这些会使函数更可预测,并且更容易调试。此外,当您的脚本增长时,您可以防止新函数或代码片段发生任何问题,bla从而改变函数中发生的情况。

通常,如果您需要函数中的变量,请将其作为变量传递。但是,R 确实允许从函数内部到函数外部进行作用域,反之亦然。另请参阅此最近的问题以获取更多信息。

于 2012-10-09T15:28:15.050 回答