Example with R: Consistency in aggregation and rebasing

It is useful to finish this section of the course with a couple examples in R. The first example shows that a geometric index is consistent in aggregation. Calculating the index in two steps gives the same answer as the direct calculation.

# Bring in gpindex library
library(gpindex)

# Make some price relatives
dat <- data.frame(relative = c(1.1, 1.2, 0.9, 1.1),
                  weight = c(0.25, 0.3, 0.3, 0.15),
                  group = letters[c(1, 1, 2, 2)])
dat
##   relative weight group
## 1      1.1   0.25     a
## 2      1.2   0.30     a
## 3      0.9   0.30     b
## 4      1.1   0.15     b
# Calculate geometric index for group a and b relatives
index_ab <- sapply(split(dat, dat$group), 
                   function(x) geometric_mean(x$relative, x$weight) * 100)
index_ab
##         a         b 
## 115.34655  96.22603
# Aggregate lower-level indices
index_top <- geometric_mean(index_ab, tapply(dat$weight, dat$group, sum))
index_top
## [1] 106.3125
# Same as the direct calculation
geometric_mean(dat$relative, dat$weight) * 100
## [1] 106.3125

The second example shows how to rebase a price index—simply divide the index series by the value of the index in the new base period.

# Make an index over 12 periods with period 0 = 100
index <- data.frame(period = 0:11, value = c(100, sample(90:130, 11)))
index
##    period value
## 1       0   100
## 2       1    95
## 3       2    98
## 4       3    92
## 5       4   103
## 6       5    93
## 7       6    99
## 8       7   128
## 9       8   115
## 10      9   104
## 11     10   114
## 12     11    91
# Rebase the index so that period 6 = 100
transform(index, value = value / value[period == 6] * 100)
##    period     value
## 1       0 101.01010
## 2       1  95.95960
## 3       2  98.98990
## 4       3  92.92929
## 5       4 104.04040
## 6       5  93.93939
## 7       6 100.00000
## 8       7 129.29293
## 9       8 116.16162
## 10      9 105.05051
## 11     10 115.15152
## 12     11  91.91919