Skip to content
Back to formatted view

Raw Message

Message-ID: <941871A13165C2418EC144ACB212BDB001B19F13@dshsmxoly1504g.dshs.wa.lcl>
Date: 2010-12-06T17:21:07Z
From: Nordlund, Dan (DSHS/RDA)
Subject: How can I refer to actual (n) and previous (n-1) elements in a vector?
In-Reply-To: <blu150-w30F4C465C9166B255AE1F8A92B0@phx.gbl>

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Marianne Stephan
> Sent: Monday, December 06, 2010 9:13 AM
> To: r-help at r-project.org
> Subject: [R] How can I refer to actual (n) and previous (n-1) elements
> in a vector?
> 
> 
> 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]]

How about something like

v[-n] +  v[-1]

Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204