[R] spped up a function

Jim Holtman
Wed, 03 Jul 2013 09:42:28 -0000

first thing to do when trying to speed up a function is to see where it is
spending its time.  take a subset of the data and use Rprof to profile the code.
my guess is that a lot of time is taken up in the use of dataframes.  see if you
can use matrices instead.

Sent from my iPad

On Jul 2, 2013, at 13:47, Santiago Guallar <sguallar at yahoo.com> wrote:

> Hi,
>
> I have written a function to assign the values of a certain variable
'wd' from a dataset to another dataset. Both contain data from the same
time period but differ in the length of their time intervals: 'GPS' has
regular 10-minute intervals whereas 'xact' has irregular intervals. I
attached simplified text versions from write.table. You can also get a dput of
'xact' in this address:
http://www.megafileupload.com/en/file/431569/xact-dput.html).
> The original objects are large and the function takes almost one hour to
finish.
> Here's the function:
>
> fxG= function(xact, GPS){
> l <- rep( 'A', nrow(GPS) )
> v <- unique(GPS$Ring) # the process is carried out for several
individuals identified by 'Ring'
> for(k in 1:length(v) ){
> I = v[k]
> df <- xact[xact$Ring == I,]
> for(i in 1:nrow(GPS)){
> if(GPS[i,]$Ring== I){# the code runs along the whole data.frame for each i;
it'd save time to make it stop with the last record of each i instead
> u <- df$timepos <= GPS[i,]$timepos
> # fill vector l for each interval t from xact <= each interval from GPS
(take the max if there's > 1 interval)
> l[i] <- df[max( which(u == TRUE) ),]$wd
> }
> }
> }
> return(l)}
>
> vwd <- fxG(xact, GPS)
>
>
> My question is: how can I speed up (optimize) this function?
>
> Thank you for your help
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.