As suggested diff
will do what you are looking for. If your dataset is large or there are groups you can try dplyr.
require(dplyr)
dat <- read.table(header = TRUE, text = "Year Revenue
2001 1.23
2002 23.4
2003 12.4
2004 18.0")
mutate(dat, yoy = Revenue - lag(Revenue))
Year Revenue yoy
1 2001 1.23 NA
2 2002 23.40 22.17
3 2003 12.40 -11.00
4 2004 18.00 5.60
Edit: In reply to Eddi's comment. There also seem to be some differences in how data is copied. See output from dplyr's changes
below.
> dplyr_dat <- mutate(dat, yoy = Revenue - lag(Revenue))
> dplyr::changes(dat, dplyr_dat)
Changed variables:
old new
yoy 0x10d951400
Changed attributes:
old new
names 0x10c3161b8 0x10deeb128
class 0x101ca6568 0x103668108
row.names 0x10c233f88 0x100c98a68
> diff_dat <- within(dat, yoy <- c(NA, diff(Revenue)))
> dplyr::changes(dat, diff_dat)
Changed variables:
old new
Year 0x10c316180 0x11086b9f0
Revenue 0x1036b2120 0x1070c0f28
yoy 0x110118a40
Changed attributes:
old new
names 0x10c3161b8 0x10c310ff8
class 0x101ca6568 0x10f4ce7a8
row.names 0x10c1d6a38 0x10f7dca78