R中的全局变量和局部变量

R中的全局变量和局部变量,r,R,我是R的新手,我对R中局部变量和全局变量的用法非常困惑 我在互联网上读到一些帖子,上面说如果我使用函数中声明的变量是该函数的局部变量。例如: foo <- function() { bar <- 1 } foo() bar 在这种情况下,可以从功能外部访问条 bar <- "global" # local will create a new environment for us to play in local({ bar <- "local"

我是R的新手,我对R中局部变量和全局变量的用法非常困惑


我在互联网上读到一些帖子,上面说如果我使用函数中声明的变量是该函数的局部变量。例如:

foo <- function() {
    bar <- 1
}
foo()
bar
在这种情况下,可以从功能外部访问

bar <- "global"
# local will create a new environment for us to play in
local({
    bar <- "local"
    print(bar)
})
#[1] "local"
bar
#[1] "global"

但是,与C、C++或许多其他语言不同,括号不能确定变量的范围。例如,在以下代码段中:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

沿着同样的路线再多一点

attrs <- {}

attrs.a <- 1

f <- function(d) {
    attrs.a <- d
}

f(20)
print(attrs.a)

attrs除了这些答案之外还需要运行一些代码:
globalenv();globalenv()%%>%parent.env;globalenv()%%>%parent.env%%>%parent.env
,…@同构,
错误:找不到函数“%%>”
。这是另一种形式的任务吗?R-help上的相关线程:。@AaronMcDaid嗨,很抱歉没有早点回复!这是来自
require(magrittr)
。这是一种在右边(
x | f1 | f2 | f3
)而不是左边(
f3(f2(f1(x)))
)应用函数的方法。
test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found
bar <- "global"
foo <- function(){
    bar <- "in foo"
    baz <- function(){
        bar <- "in baz - before <<-"
        bar <<- "in baz - after <<-"
        print(bar)
    }
    print(bar)
    baz()
    print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
bar <- "global"
foo <- function(){
    bar <- "in foo"   
    baz <- function(){
        assign("bar", "in baz", envir = .GlobalEnv)
    }
    print(bar)
    baz()
    print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
bar <- "global"
# local will create a new environment for us to play in
local({
    bar <- "local"
    print(bar)
})
#[1] "local"
bar
#[1] "global"
attrs <- {}

attrs.a <- 1

f <- function(d) {
    attrs.a <- d
}

f(20)
print(attrs.a)
attrs <- {}

attrs.a <- 1

f <- function(d) {
   attrs.a <<- d
}

f(20)
print(attrs.a)