Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get apply functions to have side effects?

I would like the function that gets called by an apply function to have side effects in the global scope, i.e. to affect variables in the global scope. This doesn't work as you can see:

library(zoo)
test=1
rollapply(1:10, width=2, function(x) test=test+1)
# [1] NA NA NA NA NA NA NA NA NA
test
# 1

I would like test to get incremented every time function(x) gets called unfortunately test is still 1 after rollapply was executed. Is it possible to get around that?

like image 932
Wicelo Avatar asked Oct 27 '25 16:10

Wicelo


1 Answers

Normally, R does not support changing variables out side of the scope of a function. The reason for this is to decrease the interconnectedness of your code. This is a good thing, as it makes it easier to reason what a particular piece of code is doing, without having to take into account all the context around it. Especially in larger programs, this can create very hard to fix bugs.

However, using the <<- operator you overwrite this behavior:

a = 1
spam = function() {
    a <<- a + 1
}
spam()
a
[1] 2

However, this if normally not needed and discouraged.

Normally, functions do not keep state, i.e. once a function is done all information inside the function is discarded. Have a look at closures to get functions that do keep state, which might solve your issue (which you did not state).

like image 173
Paul Hiemstra Avatar answered Oct 30 '25 06:10

Paul Hiemstra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!