A few months ago, I was doing some training on data science for actuaries, and I started to get interesting puzzeling questions. For instance, Fleur was working on telematic data, and she’s been challenging my (rudimentary) knowledge of R. As claimed by Donald Knuth, “*we should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil*“. So usually, in my courses, and my training, codes are very basic, and easy to understand. But usually poorly efficient. Since I was challenged, to work on very large datasets, we’ve been working on R functions to manipulate those possibly (very) large dataset, and to run some simple functions as fast as possible (with simple filter and aggregation functions).

In order to illustrate, let us generate our “large” telematic dataset. Assume that we have 10,000 drivers, each of them drives about 200 times, and each time, we have, say, 80 locations. That mean around 160 million observations. It is “large”, but not huge.

> rm(list=ls()) > N_id=10000 > N_tr=200 > T_tr=80

In order to have a code as general as possible, assume that we have some kind of randomness,

> set.seed(1) > N=rpois(N_id,N_tr) > N_traj=rpois(sum(N),T_tr)

By “observation”, we consider a driver Id., a Trajectory Id., and a location (latitude and longitude) at some specific dates (e.g. every 15 sec.). Again, just because we want some dataset to illustrate, swe will draw drivers’s home randomly (here uniformly on some square)

> origin_lat=runif(N_id,-5,5) > origin_lon=runif(N_id,-5,5)

And, then, from those locations, we generate a 2-dimensional random walk,

> lat=lon=Traj_Id=rep(NA,sum(N_traj)) > Pers_Id=rep(NA,length(N_traj)) > s=1 > for(i in 1:N_id){Pers_Id[s:(s+N[i])]=i;s=s+N[i]} > s=1 > for(i in 1:length(N_traj)){lat[s:(s+N_traj[i])]=origin_lat[Pers_Id[i]]+ + cumsum(c(0,rnorm(N_traj[i]-1,0,sd=.2))); + lon[s:(s+N_traj[i])]=origin_lon[Pers_Id[i]]+ + cumsum(c(0,rnorm(N_traj[i]-1,0,sd=.2))); + s=s+N_traj[i]}

We have something which looks like

Continue reading Working with “large” datasets, with dplyr and data.table