prices <- data.frame(
price = 1:6,
product = factor(c("a", "b")),
period = factor(c(1, 1, 2, 2, 3, 3))
)
with(prices, back_period(period, product))
# Make fixed-base price relatives.
with(
prices,
price / price[back_period(period, product, offset = nlevels(period))]
)
# Change the base period with relevel().
with(
prices,
price / price[
back_period(relevel(period, "2"), product, offset = nlevels(period))
]
)
Run the code above in your browser using DataLab