# How to get hourly diff from cumulative daily data R

I have data in two columns:

```DateTime    Profit
20130319T01  5
20130319T02  135
20130319T03  245
20130320T01  10
20130320T02  115
```

and I want to create a column that has the diff for each hour BUT the problem is that Profit resets to zero each day. I want to get the following:

```DateTime     Diff
20130319T01  5
20130319T02  130
20130319T03  110
20130320T01  10
20130320T02  105
```

Assuming the format of your DateTime character vector is always "YYYYMMDD" then you can use the ddply function from plyr to get what you want:

```require(plyr)
df\$Date <- substr( df\$DateTime , 1 , 8 )
ddply( df ,  .(Date)  , summarise , Diff = diff(c(0,Profit)) )
#     Date Diff
#1 20130319    5
#2 20130319  130
#3 20130319  110
#4 20130320   10
#5 20130320  105
```

Another way using base's ave:

```within(df, { Profit_diff <- ave(Profit, list(gsub("T.*\$", "", DateTime)),
FUN=function(x) c(x[1], diff(x)))})

#      DateTime Profit Profit_diff
# 1 20130319T01      5           5
# 2 20130319T02    135         130
# 3 20130319T03    245         110
# 4 20130320T01     10          10
# 5 20130320T02    115         105
```