Data Preparation – Part I

The R language provides tools for modeling and visualization, but is still an excellent tool for handling/preparing data. As C++ or python, there is some tricks that bring performance, make the code clean or both, but especially with R these choices can have a huge impact on performance and the “size” of your code. A seasoned R user can manage this effectively, but this can be a headache to a new user. SO, in this series of posts i will present some data preparation techniques that anyone should know about, at least the ones i know!

1. Using apply, lappy, tapply

Sometimes the apply’s can make your code faster, sometimes just cleaner. BUT the fact is that, at least in R, is recommended avoid for loops. So, instead of using loops, you can iterate over matrixes, lists and vectors using these functions. As an example see this code:

[sourcecode language=”r”]
matriz <- matrix(round(runif(9,1,10),0),nrow=3)
apply(matriz, 1, sum) ## sum by row
apply(matriz, 2, sum) ## sum by column

Particularly in this example there is no gain on performance, but you get a cleaner code.

Talking about means, sometimes tapply can be very usefull in this regard. Let’s say you want to get means by group, you can have this with one line too. For example, considering the mtcars dataset:


[sourcecode language=”r”]
tapply(mtcars$hp, mtcars$cyl, mean)

and you can have the mean power by cylinder capacity. This function is very usefull on descriptive analysis. BUT sometimes you have lists, not vectors. In this case just use lappy or sapply (simplify the output). Let’s generate some data:

[sourcecode language=”r”]
lista <- list(a=c(‘one’, ‘tow’, ‘three’), b=c(1,2,3), c=c(12, ‘a’))

Each element of this list is a vector. Let’s say you want to know how many elements there is in each vector:

[sourcecode language=”r”]
lapply(lista, length) ## return a list
sapply(lista, length) ## coerce to a vector

2. Split, apply and recombine

This technique you must know. Basically we split the data, apply a function and combine the results. There is a package created with this in mind. But we will use just base R functions: split, *apply and cbind() ou rbind() when needed. Looking again at mtcars dataset, let’s say we want fit a model of mpg against disp, grouped by gears,  and compare the regression coefficients.


[sourcecode language=”r”]
data <- split(mtcars, mtcars$gear) ## split
fits <- lapply(data, function(x) return(lm(x$mpg~x$disp)$coef)) ## apply, fits) ## recombine

This technique is powerfull. You can use at different contexts.

Next part i will talk about some tricks with dates.

Share Button