Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

I am a newbie for R, and I am quite confused with the usage of local and global variables in R.

I read some posts on the internet that say if I use = or <- I will assign the variable in the current environment, and with <<- I can access a global variable when inside a function.

However, as I remember in C++ local variables arise whenever you declare a variable inside brackets  {}, so I'm wondering if this is the same for R? Or is it just for functions in R that we have the concept of local variables.

I did a little experiment, which seems to suggest that only brackets are not enough, am I getting anything wrong?

{

   x=matrix(1:10,2,5)

}

print(x[2,2])

[1] 4

1 Answer

0 votes
by

The variables that are declared inside a function are local to that function. While 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.

For example:

fun <- function() {

  var1 <- 1

}

fun()

var1

Error: object 'var1' not found

In most of the cases the <<- operator will assign to variables already present in the global environment or create a new variable in the global environment even if you're inside a function. 

The <<- operator checks the parent environment for a variable with the name of the new variable. 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). 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.

For example:

 fun <- function() {

+   var1 <<- 1

+ }

> fun()

> var1

[1] 1

If you want to assign an object to the global environment you can use the assign function and tell it explicitly that you want to assign globally.

For example:

 var1 <- "global"

 fun1 <- function(){

   var1 <- "in fun1"  

   

   fun2 <- function(){

     assign("var1", "in fun2", envir = .GlobalEnv)

     }

   print(var1)

   fun2()

   print(var1)

 }

 var1

[1] "global"

 fun1()

[1] "in fun1"

[1] "in fun1"

var1

[1] "in fun2"

In the above example, the assign function did not consider the copy of the var1 inside of fun1 because we mentioned it exactly where to look. However, this time the value of var1 in the global environment was changed because we explicitly assigned it there.

Now If you want to create a local variable, you can use the local function as follows:

var1 <- "global"

local({

  var1 <- "local"

  print(var1)

})

[1] "local"

> var1

[1] "global"

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...