# A Little R Counter

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I recently read a great post about environments in R, which featured this little bit of code:**mickeymousemodels**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

> createCounter <- function(value) { function(i) { value <<- value+i} } > counter <- createCounter(0) > counter(1) > a <- counter(0) > a [1] 1 > counter(1) > counter(1) > a <- counter(1) > a [1] 4 > a <- counter(5) > a [1] 9

I found this particular snippet quite interesting, but also somewhat difficult to read. Here’s my own version, inspired by the code in demo(scoping):

CreateCounter <- function(curr.count) { list( increment = function(amount) { curr.count <<- curr.count + amount }, value = function() { return(curr.count) } ) }

My function is a little longer, but it lets you do this:

> counter <- CreateCounter(10) > counter$increment(9) > counter$value() [1] 19

To

**leave a comment**for the author, please follow the link and comment on their blog:**mickeymousemodels**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.