Programing

R의 전역 및 지역 변수

crosscheck 2020. 7. 15. 07:41
반응형

R의 전역 및 지역 변수


나는 R의 초보자이며 R의 지역 및 전역 변수 사용법과 혼동됩니다.

인터넷 에서 현재 환경에서 변수를 사용 =하거나 <-할당 할지 여부를 나타내는 게시물을 읽었 <<-으며 함수 내부에서 전역 변수에 액세스 할 수 있습니다.

그러나 C ++에서 기억할 때 괄호 안에 변수를 선언 할 때마다 로컬 변수가 발생 {}하므로 이것이 R에 대해 동일한 지 궁금합니다. 아니면 지역 변수의 개념을 갖는 것이 R의 함수 일뿐입니다 .

나는 약간의 실험을했는데, 대괄호만으로는 충분하지 않다고 제안하는 것 같습니다.

{
   x=matrix(1:10,2,5)
}
print(x[2,2])
[1] 4

함수 내부에 선언 된 변수는 해당 함수에 로컬입니다. 예를 들어 :

foo <- function() {
    bar <- 1
}
foo()
bar

다음과 같은 오류가 발생 Error: object 'bar' not found합니다.

bar전역 변수 를 만들려면 다음을 수행해야합니다.

foo <- function() {
    bar <<- 1
}
foo()
bar

이 경우 bar기능 외부에서 액세스 할 수 있습니다.

그러나 C, C ++ 또는 다른 많은 언어와 달리 대괄호는 변수의 범위를 결정하지 않습니다. 예를 들어 다음 코드 스 니펫에서

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

yif-else진술 후에도 접근 가능 합니다.

잘 말하지만, 중첩 환경을 만들 수도 있습니다. 사용 방법을 이해하기 위해이 두 링크를 살펴볼 수 있습니다.

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

여기 작은 예가 있습니다.

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

<- 현재 환경에서 할당합니다.

When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.

In most cases <<- will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.

This might illustrate what is going on.

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"

The first time we print bar we haven't called foo yet so it should still be global - this makes sense. The second time we print it's inside of foo before calling baz so the value "in foo" makes sense. The following is where we see what <<- is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-. This is because <<- doesn't look in the current environment (unless you're in the global environment in which case <<- acts like <-). So inside of baz the value of bar stays as "in baz - before <<-". Once we call baz the copy of bar inside of foo gets changed to "in baz" but as we can see the global bar is unchanged. This is because the copy of bar that is defined inside of foo is in the parent environment when we created baz so this is the first copy of bar that <<- sees and thus the copy it assigns to. So <<- isn't just directly assigning to the global environment.

<<- is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.

Now I change the <<- to an assign statement and we can see what effect that has:

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"

So both times we print bar inside of foo the value is "in foo" even after calling baz. This is because assign never even considered the copy of bar inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.

Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local function.

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

A bit more along the same lines

attrs <- {}

attrs.a <- 1

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

f(20)
print(attrs.a)

will print "1"

attrs <- {}

attrs.a <- 1

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

f(20)
print(attrs.a)

Will print "20"

참고URL : https://stackoverflow.com/questions/10904124/global-and-local-variables-in-r

반응형