I want to calculate a moving difference for my dataset below.

79 views Asked by At

enter image description here

How do I add another column with a moving difference of Column2?

For Example: I want to add a column where it will have the following values: (0,-372706.6,-284087.1, -119883.7, etc.)

1

There are 1 answers

0
Badger On BEST ANSWER

Here's a way to go about it.

## For a small dataset

x <- data.frame(matrix(nrow=7,ncol=2,c(0,12,1,10,2,9.5,3,8,4,7,5,5,6,2),byrow = T))
names(x) <- c("Time","Count")

x[1,"Diff"] <- NA
x[2:nrow(x),"Diff"] <- rev(diff(rev(x$Count)))

There is a way to do it with the plyr package as well.