A Little R Counter

June 11, 2011
By

(This article was first published on mickeymousemodels, and kindly contributed to R-bloggers)

I recently read a great post about environments in R, which featured this little bit of code:

> 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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)