An embedded and charset-unspecified text was scrubbed... Name: not available Url: https://stat.ethz.ch/pipermail/r-help/attachments/20071211/75d6420f/attachment.pl
Alternative to For Loop?
4 messages · tom soyer, Duncan Murdoch, Romain Francois
tom soyer wrote:
Hi,
I am doing a calculation on a long series using a For Loop. Here is an
example of the calculation:
accumulate=function(x){
y=0
z=0
for(i in 1:length(x)){
y=y+x[i]
z=c(z,y)
}
return(z[2:length(z)])
}
x=c(1:10)
x
[1] 1 2 3 4 5 6 7 8 9 10
accumulate(x)
[1] 1 3 6 10 15 21 28 36 45 55 Although the For Loop works, looping through an array is time consuming and inefficient when the series is large. Does anyone know a faster way of doing the same calculation? Thanks!
cumsum(x) is what you want. Duncan Murdoch
Un texte encapsul? et encod? dans un jeu de caract?res inconnu a ?t? nettoy?... Nom : non disponible Url : https://stat.ethz.ch/pipermail/r-help/attachments/20071211/efaefe2d/attachment.pl
An embedded and charset-unspecified text was scrubbed... Name: not available Url: https://stat.ethz.ch/pipermail/r-help/attachments/20071211/0bfd4285/attachment.pl