From: Oleg Sklyar <osklyar_at_ebi.ac.uk>

Date: Tue 30 Jan 2007 - 12:15:29 GMT

> [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
*

*>
*

*>
*

*>
*

Date: Tue 30 Jan 2007 - 12:15:29 GMT

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

-- Dr Oleg Sklyar * EBI/EMBL, Cambridge CB10 1SD, England * +44-1223-494466 ______________________________________________ R-devel@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-develReceived on Tue Jan 30 23:25:31 2007

Archive maintained by Robert King, hosted by
the discipline of
statistics at the
University of Newcastle,
Australia.

Archive generated by hypermail 2.1.8, at Tue 30 Jan 2007 - 15:31:08 GMT.

*
Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel.
Please read the posting
guide before posting to the list.
*