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"