Site icon R-bloggers

Another Rchievement of the day

[This article was first published on ASCIImoose: William K. Morris’s Blog » R, 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.

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 their blog: ASCIImoose: William K. Morris’s Blog » R.

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.