Another Rchievement of the day

August 24, 2011
By

(This article was first published on ASCIImoose: William K. Morris’s Blog » R, and kindly contributed to R-bloggers)

Time for another Rchievement of the day.

> while (!any(as.logical(x <- rbinom(3, 1, .5)))) {}
> [1] 0 1 0

This is a neat little example demonstrating the power of control flow (type ?Control in R to find out more). But perhaps a not-so obvious way of using it. So what does this snippet of code do? It simply makes three Bernoulli samples with p=.5 (or three fair coin flips if you like). But it will only return sets that aren’t all zeros. There are probably lots of other ways to do this and it’s a fairly trivial example. But the concept is useful and has wider application.

So what exactly is going on. The point of while is to keep evaluating the expression in the set of curly brackets as long as the result of the logical statement enclosed in the first set of brackets is TRUE. In this example the expression in the curly brackets is absent, so all while does is keep checking the result of the first expression. This is where it gets interesting. Because of R’s object orientation we can assign some value to x and interrogate the properties of x at the same time. In this case I’ve asked, “are there any 1’s?”, and if so while will stop evaluating. Which is exactly what we wanted. This technique could be useful for quite a few things. In my case I have been using it to sub-sample some large datasets but making sure the sub-samples meet certain conditions. Another use might be to evaluate some external process or the properties of a local file or website. As Brian Butterfield would say, “it’s up to you”.


To leave a comment for the author, please follow the link and comment on his blog: ASCIImoose: William K. Morris’s Blog » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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.