[R] calculate difference of consecutive cells in vector

Christos Hatzis christos at silicoinsights.com
Wed Mar 22 21:57:47 CET 2006


Try

my.data$output <- diff(my.data$var1)

-Christos 

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Max Kauer
Sent: Wednesday, March 22, 2006 3:36 PM
To: r-help at stat.math.ethz.ch
Subject: [R] calculate difference of consecutive cells in vector

Hi
in dataframe I want to subtract the "next" value in the list from the former
one to get this:

name     var1  output
a           9    506
b         515    512
c        1027    453

so I subtract: table$var1[2]-table$var1[1] and write it into table$output[1]
etc..

I did this with:
   
for (i in 1:(length(table$var1)){
	table$output[i] <- table$var1[i+1]-table$var1[i] }

it works but it get extremely slow for a large table.

I bet there is a better way to do this in R with "sapply" or something
similiar, but I couldn't figure out how.

I'd apprechiate any idea
Thanks!
Max

--
"Feel free" mit GMX FreeMail!
Monat f|r Monat 10 FreeSMS inklusive! http://www.gmx.net




More information about the R-help mailing list