Wednesday, January 27, 2016

Graphing in R

OK, I'll give it that much: graphing in R is trivial. I took an example diagram from the class text (cumulative proportion of coin tosses coming up heads) and tried to replicate it. Even this code is pretty verbose; you could jam all the graph commands into a single call. But, I don't like going for super-concise code as it's too hard for the next person to figure out what you did.
CummFlips = function(n, p)
  cumsum(rbinom(n, 1, p)) / (1:n)

plot.new()
plot.window(c(1,500), c(0,1), log="x")
plot.xy(xy.coords(CummFlips(500, .5)), "o")
axis(1)
axis(2)
title("Running Proportion of Heads",NULL,
  "Flip Number","Proportion")
From what I've sorted through online, the R crowd isn't nearly as fanatical about sticking to the functional roots in the language as are the adherents of it's progenitors. I think a lot of R practitioners would have put the binomial vector in a variable rather than using nested functions. As a C# programmer, I certainly have no problem with using variables, but it doesn't seem necessary and if you can't even get past an exercise this simple without trashing the language design philosophy, you might want to move on to something else.

The graph (at least the left hand portion) obviously changes each time you run this. Here's an example output:


No comments:

Post a Comment