Hi, I'd like to take difference for a sequence a between a_i and a_i-2, for instance, a<-c(2,3,4,8,1) I need (2, 5, -3) as a result. If not using a for loop, can anyone help me? Thanks a lot. Dot -- View this message in context: http://www.nabble.com/R-help--how-to-take-difference-in-next-two-elements-tp18927968p18927968.html Sent from the R help mailing list archive at Nabble.com.
Chuck Cleland
2008-Aug-11 16:07 UTC
[R] R-help? how to take difference in next two elements
On 8/11/2008 11:26 AM, dott wrote:> Hi, > > I'd like to take difference for a sequence a between a_i and a_i-2, for > instance, > a<-c(2,3,4,8,1) > I need (2, 5, -3) as a result. If not using a for loop, can anyone help me? > Thanks a lot. > > Dota <- c(2,3,4,8,1) diff(a, lag=2) [1] 2 5 -3 ?diff -- Chuck Cleland, Ph.D. NDRI, Inc. (www.ndri.org) 71 West 23rd Street, 8th floor New York, NY 10010 tel: (212) 845-4495 (Tu, Th) tel: (732) 512-0171 (M, W, F) fax: (917) 438-0894
Gabor Grothendieck
2008-Aug-11 16:13 UTC
[R] R-help? how to take difference in next two elements
Here are a couple of ways:> tail(a, -2) - head(a, -2)[1] 2 5 -3> c(ts(a) - lag(ts(a), -2))[1] 2 5 -3 On Mon, Aug 11, 2008 at 11:26 AM, dott <dorothy99 at gmail.com> wrote:> > Hi, > > I'd like to take difference for a sequence a between a_i and a_i-2, for > instance, > a<-c(2,3,4,8,1) > I need (2, 5, -3) as a result. If not using a for loop, can anyone help me? > Thanks a lot. > > Dot > -- > View this message in context: http://www.nabble.com/R-help--how-to-take-difference-in-next-two-elements-tp18927968p18927968.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help at 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. >
Please use R's help resources before posting. help.search("difference") will give you your answer (?diff). -- Bert Gunter Genentech -----Original Message----- From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of dott Sent: Monday, August 11, 2008 8:27 AM To: r-help at r-project.org Subject: [R] R-help? how to take difference in next two elements Hi, I'd like to take difference for a sequence a between a_i and a_i-2, for instance, a<-c(2,3,4,8,1) I need (2, 5, -3) as a result. If not using a for loop, can anyone help me? Thanks a lot. Dot -- View this message in context: http://www.nabble.com/R-help--how-to-take-difference-in-next-two-elements-tp 18927968p18927968.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help at 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.