Saturday, July 2, 2011

The R apply function – a tutorial with examples

Today I had one of those special moments that is uniquely associated with R. One of my colleagues was trying to solve what I term an 'Excel problem'. That is, one where the problem magically disappears once a programming language is employed. Put simply, the problem was to take a range, and randomly shift the elements of the list in order. For example, 12345 could become 34512 or 51234.

The list in question had forty-thousand elements, and this process needed to be repeated numerous times as part of a simulation. Try doing this in Excel and you will go insane: the shift function is doable but resource intensive. After ten minutes of waiting for your VBA script to run you will be begging for mercy or access to a supercomputer. However, in R the same can be achieved with the function:
translate<-function(x){
  if (length(x)!=1){
    r<-sample(1:(length(x)),1)
    x<-append(x[r:length(x)],x[1:r-1])
  }
  return(x)
}
My colleague ran this function against his results several thousand times and had the pleasure of seeing his results spit out in less than thirty seconds: problem solved. Ain't R grand.

More R magic courtesy of the apply function
The translate function above is not rocket science, but it does demonstrate how powerful a few lines of R can be. This is best exemplified by the incredible functionality offered by the apply function. However, I have noticed that this tool is often under-utilised by less experienced R users.

The usage from the R Documenation is as follows:
apply(X, MARGIN, FUN, ...)

where:
  • X is an array or matrix;
  • MARGIN is a variable that determines whether the function is applied over rows (MARGIN=1), columns (MARGIN=2), or both (MARGIN=c(1,2));
  • FUN is the function to be applied.
In essence, the apply function allows us to make entry-by-entry changes to data frames and matrices. If MARGIN=1, the function accepts each row of X as a vector argument, and returns a vector of the results. Similarly, if MARGIN=2 the function acts on the  columns of X. Most impressively,  when MARGIN=c(1,2) the function is applied to every entry of X. As for the FUN argument, this can be anything from a standard R function, such as sum or mean, to a custom function like translate above.

An illustrative example
Consider the code below:
# Create the matrix
m<-matrix(c(seq(from=-98,to=100,by=2)),nrow=10,ncol=10)

# Return the product of each of the rows
apply(m,1,prod)

# Return the sum of each of the columns
apply(m,2,sum)

# Return a new matrix whose entries are those of 'm' modulo 10
apply(m,c(1,2),function(x) x%%10) 

In the last example, we apply a custom function to every entry of the matrix. Without this functionality, we would be at something of a disadvantage using R versus that old stalwart of the analyst: Excel. But with the apply function we can edit every entry of a data frame with a single line command. No autofilling, no wasted CPU cycles.

In the next edition of this blog, I will return to looking at R's plotting capabilities with a focus on the ggplot2 package. In the meantime, enjoy using the apply function and all it has to offer.

Friday, June 24, 2011

Multiple plots in R: lesson zero

Today, in one of my more productive days, I managed to create a sleek R script that plotted several histograms in a lattice, allowing for easy identification of the underlying trend. Although the majority of the time taken consisted of collecting the data and making various adjustments, it took a not inconsiderable amount of work to write the code.

As I was cursing the apply function – not for the last time I am sure – I suddenly realised the insane level of productivity that I have come to see as "par for the course". The level of computational analysis that can be conducted in a few hours with nothing more than a desktop PC,  a broadband connection, and copious amounts of caffeine is phenomenal. No longer can a lack of computing power or software be blamed for a lack of productivity growth: rate-limiting factors are now exclusively human.

Here at least is my contribution to the collective intelligence of biologicals. I have noticed that the most common reason that people avoid R is that they cannot rapidly make graphs that meet the high standards of their clients. In the next few editions of this blog we will build up a basic repertoire of plotting techniques, focusing on graphics that are sickeningly impressive.

Of course, Rome was not built in a day, and a thorough knowledge of R plotting cannot be built in one. Instead we will progress one layer at a time, adding additional levels of complexity and functionality. We start with a simple script that allows us to plot several graphs at the same time, each with a different value of a key variable. Here is the output:

Figure 1: Multiple plots using par

The code
# Clear all objects
rm(list=ls())

# Create a data set using random variables
df<-data.frame(x=rnorm(160),y=runif(160),a=sample(c(1,0,-1,10),
replace=TRUE,160))

df$z<-with(df,{3*a*y+x})

# Create a function that plots the value of "z" against the "y" value
plotM<-function(l){
  
  df.temp<-df[df$a==l,]
  plot(df.temp$y,df.temp$z,xlab="Y Value",ylab="Z Value",
  main=paste("Value of key variable: ",toString(l)))
  abline(lm(df.temp$z~df.temp$y),col="red")
  
}

# Create a grid to plot the different values of "a"
par(mfrow=c(2,2))

# Loop through each value of "a" and call the plotM function
for (i in c(1,0,-1,10)){
    plotM(i)
}
  
Walk-through
The first few lines of code create a data frame with 4 variables: x,y,z,a. Three of these variables are randomly generated, with the z variable dependent upon the other 3. Suppose that we are analysing this data set, unaware of the relationship between the x,y and z variables. A preliminary inspection shows that there are only 4 observed values of a. It seems sensible to plot z against y for each of these different a values.

The relevant code to create this plot starts with the function "plotM", standing for plot Multiple. This function takes an argument "l" that determines which value of the variable we are plotting. The line

df.temp<-df[df$a==l,]

filters the data frame to include only those rows where the variable a=l. The next line simply creates a standard R plot of y versus z. Finally, we use the abline function to plot a linear fit to highlight the trend. Too easy.

Now we come to the fun part. Using the par(mfrow=c(2,2)) we create a 2x2 grid in which to place the next four plots. Whatever plots we now create will be placed sequentially into this grid. Hence we can iterate over a vector containing the values of a,  calling plotM each time. This gives us our grid.

Comments
Okay, so the graph does not look like it came from NASA – or to be honest with NASA's ailing reputation maybe it does. But note that once we have created the plotM function, we only have to write 3 lines of code to make 4 separate charts. Moreover, the code would not increase even if we were plotting 100 charts.

Of course, we have not yet even drawn upon any of R's custom plotting packages. In the next edition of this blog we will look at how to use the ggplot2 package to add colour and a wide range of other features to our graphs.

Monday, May 16, 2011

Keep It Linear Stupid: the cost of achieving perfection under pressure

"That gives you 48 hours to develop a methodology – since we haven't done one of these before – prototype the model, build it, calibrate it to client expectations, and write the report. But don't worry, the client is paying a premium for the rush."

Every analyst has been in this sort of situation. The client wants something now, and your boss has agreed to deliver it. The trouble is that before that perfectly crafted 3-line email three is sent, accompanied by a hefty invoice, you actually have to build the thing. What is more, lack of time is no excuse for sloppy work. No mistakes, after all we're professionals.

Working to a deadline
The Mythical Man-Month is the best book about managing projects to a deadline that I have ever read.  Although focused on software engineering, the book has lessons that apply to project management in any technical field. The author, Frederick P. Brooks, provides a mathematical argument for why adding manpower to a technical project that is running late makes it later (Brook's Law).  The problem is that  time spent getting new people up to speed (initiation) and coordinating additional manpower (co-ordination) exceeds the additional productivity. There is a fixed time-cost to incorporate a new worker onto a project. Unless the project has a long way to go, adding people just slows it down.

An obvious corollary to Brook's Law is that there is a minimum time required to complete any project that is directly proportional to its complexity. Moreover, this minimum time corresponds to a unique number of workers: at some point additional manpower has decreasing returns to scale in the form of co-ordination and initiation costs. What does this mean for your 48-hour rush-job? It is a one-man, or at most two-man, show. Looks like you will be staying back in the office on your own.

No mistakes...well sort of
The big consultancy houses and banks have built a powerful image for their industries over time. That image is in every logo, every website, every banner at a conference. The image is one of flawlessness, of crystalline perfection, of exacting standards.

This notion of a clinical, relentless pursuit of perfection has managed to convince the non-technical members of society that for the right price perfection is not only achievable, but the norm. On the first day of my first job, I remember my boss emphasising the many processes that were in place to prevent errors. My boss was, naturally, a manager. Managers do not run the numbers: if no-one finds an error then they assume there were none to find. I rapidly realised that although it was unacceptable for errors to be discovered, it was perfectly acceptable for errors to exist.

A one page document can contain perfect spelling; a single table of data can be copied exactly from another source. But the problem for the analyst is managing complexity. Large documents are more likely to house inconsistencies; models that attempt to capture more variables are more prone to calculation errors. The Law of Large Numbers sucks, doesn't it.

Of course, the notion of perfection is somewhat flexible for the rush-job.  The odd inaccurate assumption is forgivable,  as is a minor inconsistency in the results. But if there is a major mistake, don't dare blame the deadline. So how do you avoid mistakes during a rush-job? The answer is a variation of the "Keep It Simple Stupid" (KISS) rule.

Keep it Linear Stupid
Let's assume for a second that you are young and naive, some might even say a cock-eyed optimist who has gotten caught up in the world of international modelling intrigue. Despite the impending deadline, you nevertheless are determined to capture every aspect of the phenomenon at hand. One crucial variable is clearly quadratic,  and to assume it is linear would be a travesty against all that mathematics stands for. Was it all for nothing, Archimedes? 

You have a choice in front of you: you pick the blue line – the complexity ends, you wake up in your bed and believe whatever you want to believe. You pick the red line – you stay in mathematical wonderland and this model is going to show you just how deep the rabbit-hole goes. You are young, you are fearless, you are stupid – you choose the red line.
"I know what you're asking yourself: why oh why didn't I pick the blue line?"

Down the rabbit-hole
Okay, so its not as bad as waking up in a petri dish to find that you have a massive fire-wire port in the back of your skull. But by 2 am in the morning of the second day, you are going to wish that you could go back and choose that blue line – I guarantee it.

You see the problem with a rush job is that you don't have time to go back. The client expects the results to make sense, and there is always one number that can't be explained by anything other than an error. But when you go to iron it out, that red line comes back to haunt you. Every tiny alteration to the inputs results in a non-linear change to the results. 

Ordinarily, this is fine as you have plenty of time to get it right  Given time you would be able to rework the model, but that is time you don't have. Every time you pin down one set of numbers, another one jumps out of its place. Non-linearity is hard to explain and even harder to defend, especially when you know that there may be errors. If you are lucky, you will be able to explain away the aberration. If not, you have a report that may as well be lit with a neon sign saying "Error: Division by zero".

The price of sanity
Okay, so you learned your lesson. Next time you get a rush job, you restrict your analysis to the one-dimensional case (and even that seems gutsy), tether your key variables to a stake in the numeric al equivalent of Alcatatraz, and assume that everything from the inflation rate to the diffusion of information throughout the economy can be approximated by a linear function. Nice job.

You have done well by your boss, you have done well by yourself. You have even done right be your client, as they have the report they wanted. But what good is it? The purpose of quantitative analysis is to enlighten decision making, to add something that could not have been uncovered by logic alone. Once you have removed all complexity, you have also removed all value. You have created consistency and clarity but at vulgar cost. In truth, you have obscured more than you have explained.

An analyst often has little choice in the matter at the time, but they can make clear how banal the results are that spring from these sorts of exercises. More time may be an option, absolute internal consistency may not be essential. If the alternative is simplification ad absurdum, then it may be better to pass on the job. 

Keep it simple, keep it trivial. Keep it linear? Stupid.