df <- data.frame(
price = 1:6,
product = factor(c("a", "b")),
period = factor(c(1, 1, 2, 2, 3, 3))
)
with(df, back_period(period, product))
# Make period-over-period price relatives
with(df, price / price[back_period(period, product)])
# Make fixed-base price relatives
with(df, price / price[base_period(period, product)])
# Change the base period with relevel()
with(df, price / price[base_period(relevel(period, "2"), product)])
# Warning is given if the same product has multiple prices
# at any point in time
with(df, back_period(period))
Run the code above in your browser using DataLab