全局变量和作用域-R

全局变量和作用域-R,r,function,scope,global-variables,R,Function,Scope,Global Variables,我不明白为什么R中的全局范围列表不能从函数中修改,如下所示: global <<- list() f <- function(x) { global[[x]] <- "blah" } f(1) f(2) print(global) 但是,我期望得到以下结果: [[1]] [1] "blah" [[2]] [1] "blah" 为什么会这样?我必须声明列表中的每个元素也是全局的吗 对于在函数块外部声明的局部作用域变量,情况似乎也是如此 谢谢 我相信你只是被的东

我不明白为什么R中的全局范围列表不能从函数中修改,如下所示:

global <<- list()

f <- function(x) {
  global[[x]] <- "blah"
}

f(1)
f(2)
print(global)
但是,我期望得到以下结果:

[[1]]
[1] "blah"

[[2]]
[1] "blah"
为什么会这样?我必须声明列表中的每个元素也是全局的吗

对于在函数块外部声明的局部作用域变量,情况似乎也是如此


谢谢

我相信你只是被
的东西弄糊涂了,我相信你只是被
的东西弄糊涂了,因为你基本上是在使用“的,因为你在使用

[[1]]
[1] "blah"

[[2]]
[1] "blah"
global <<- list()

f <- function(x) {
  global[[x]] <- "blah"
  g(x)
  global
}

g <- function(x){
  global[[x]] <<- "newblah"
}


f(1)  #prints 'blah', despite the fact the g(x) has already updated the value

global  #prints 'newblah'
global <<- list()

f <- function(x) {
  global[[x]] <- "blah"

  g <- function(x){
    global[[x]] <<- "newblah"
  }

  g(x)
  global
}



f(1) #prints 'newblah'

global #empty