After some hours I found a bug in my code because an unexpected behaviour of the <<-
assinament operator in r. I have read the documentation and browsed on internet but I still do not understand the behaviour of the operator.
Look these two functions:
# Define a function a_counter
a_counter <- function(){
i <<- i + 1
print(i)
}
> i <- 0
> a_counter()
[1] 1
> print(i)
[1] 1
> a_counter()
[1] 2
> print(i)
[1] 2
# Define a function not_a_counter
not_a_counter <- function(){
i <- 0
i <<- i + 1
print(i)
}
> i <- 0
> not_a_counter()
[1] 0
> print(i)
[1] 1
> not_a_counter()
[1] 0
> print(i)
[1] 1
The first chunk of code runs as I expected, the variable i
in both environments (function env. and global env.) are increased in each function call.
The second chunk of code is absolutely unexpected for me. The i <<- i + 1
does not assign the value to the i
located in the function environment, but it does so in the i
located in the global environment. I expected both enviroments to be updated.