[Rd] Speed of for loops
Tom McCallum
tom.mccallum at levelelimited.com
Tue Jan 30 11:38:35 CET 2007
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. Thomas McCallum
Systems Architect,
Level E Limited
ETTC, The King's Buildings
Mayfield Road,
Edinburgh EH9 3JL, UK
Work +44 (0) 131 472 4813
Fax: +44 (0) 131 472 4719
http://www.levelelimited.com
Email: tom at levelelimited.com
Level E is a limited company incorporated in Scotland. The c...{{dropped}}
More information about the R-devel
mailing list