ddg
ddg

Reputation: 2523

Get difference to previous date in R

I have a list of deals with trading day and market value. Every (Trading)day new positions come into the list but the old one never disappear (when positions expire the value stays just constant). The list looks like as follows:

Deal Trade_Date MktValue Desidered_Col
Deal1 31.08.2012 10 +10
Deal2 31.08.2012 21 +21
Deal1 03.09.2012 12 +2
Deal2 03.09.2012 19 -2
Deal3 03.09.2012 2  +2

I would like for each deal to get the difference to the previous trade date (Desidered_Col in the above example). I would like to avoid looping just because I the list is quite long. I am using R. I would appreciate if anybody has any suggestion. Thanks!

Upvotes: 2

Views: 444

Answers (1)

Roland
Roland

Reputation: 132576

Use data.table for big datasets:

df <- read.table(text="Deal Trade_Date MktValue Desidered_Col
Deal1 31.08.2012 10 +10
Deal2 31.08.2012 21 +21
Deal1 03.09.2012 12 +2
Deal2 03.09.2012 19 -2
Deal3 03.09.2012 2  +2",header=TRUE)

library(data.table)
dt <- as.data.table(df)

diff.padded <- function(x) c(x[1],diff(x))

dt[,Desidered_Col2:=diff.padded(MktValue),by=Deal]

#    Deal Trade_Date MktValue Desidered_Col Desidered_Col2
#1: Deal1 31.08.2012       10            10             10
#2: Deal2 31.08.2012       21            21             21
#3: Deal1 03.09.2012       12             2              2
#4: Deal2 03.09.2012       19            -2             -2
#5: Deal3 03.09.2012        2             2              2

Upvotes: 3

Related Questions