Another Rchievement of the day

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”.

This entry was posted in Programming, R and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s