Hi:

This is called a 'rolling sum', for which there is a very convenient
function called rollapply() in the zoo package. You first need to convert v
to a zoo object (in this case, an indexed vector):

library(zoo)
> rollapply(zoo(v), 2, FUN = sum)
 1  2  3  4  5  6  7  8  9
 9 14  9  2  4 12 14 11  9

The second argument is the width of the window to which the function is to
be applied - in this case, you want a window of width two and a sum
function.

HTH,
Dennis

On Mon, Dec 6, 2010 at 9:13 AM, Marianne Stephan <
mariannestephan@hotmail.com> wrote:

>
> Hello,
>
>
> How can I apply a function on a vector that refers to actual (n) and
> previous elements in the vector (e.g. n-1)?
>
>
> For example:
> I would like to calculate the sum of (n-1) + n for each element of a vector
> and get a vector as a result.
>
>
> Besides others I tried this:
>
>
> v<-c(3,6,8,1,1,3,9,5,6,3)
> for (i in 1:NROW(v)){a[i]<-a[i-1]+a[i]}
>
>
> I would like to get this result:
> 9,14,9,2,4,12,14,11,9
>
>
> I would greatly appreciate your help!
> Marianne
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@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.
>

	[[alternative HTML version deleted]]

