[Rd] Speed of for loops
Oleg Sklyar
osklyar at ebi.ac.uk
Tue Jan 30 13:15:29 CET 2007
Tom,
*apply's generally speed up calculations dramatically. However, if and
only if you do a repetitive operation on a vector, list matrix which
does NOT require accessing other elements of that variable than the one
currently in the *apply index. This means in your case any of *apply
will not speed up your calculation (until you significantly rethink the
code). At the same time, you can speed up your code by orders of
magnitude using c-functions for "complex" vector indexing operations. If
you need instructions, I can send you a very nice "Step-by-step guide
for using C/C++ in R" which goes beyond "Writing R Extensions" document.
Otherwise, such questions should be posted to R-help, not Rd, please
post correspondingly.
Best regards,
Oleg
Tom McCallum wrote:
> Hi Everyone,
>
> I have a question about for loops. If you have something like:
>
> f <- function(x) {
> y <- rep(NA,10);
> for( i in 1:10 ) {
> if ( i > 3 ) {
> if ( is.na(y[i-3]) == FALSE ) {
> # some calculation F which depends on one or more of the previously
> generated values in the series
> y[i] = y[i-1]+x[i];
> } else {
> y[i] <- x[i];
> }
> }
> }
> y
> }
>
> e.g.
>
>> f(c(1,2,3,4,5,6,7,8,9,10,11,12));
> [1] NA NA NA 4 5 6 13 21 30 40
>
> is there a faster way to process this than with a 'for' loop? I have
> looked at lapply as well but I have read that lapply is no faster than a
> for loop and for my particular application it is easier to use a for loop.
> Also I have seen 'rle' which I think may help me but am not sure as I have
> only just come across it, any ideas?
>
> Many thanks
>
> Tom
>
>
>
--
Dr Oleg Sklyar * EBI/EMBL, Cambridge CB10 1SD, England * +44-1223-494466
More information about the R-devel
mailing list