Movatterモバイル変換


[0]ホーム

URL:


Title:Price Index Aggregation
Version:0.8.3
Description:Most price indexes are made with a two-step procedure, where period-over-period elementary indexes are first calculated for a collection of elementary aggregates at each point in time, and then aggregated according to a price index aggregation structure. These indexes can then be chained together to form a time series that gives the evolution of prices with respect to a fixed base period. This package contains a collection of functions that revolve around this work flow, making it easy to build standard price indexes, and implement the methods described by Balk (2008, <doi:10.1017/CBO9780511720758>), von der Lippe (2007, <doi:10.3726/978-3-653-01120-3>), and the CPI manual (2020, <doi:10.5089/9781484354841.069>) for bilateral price indexes.
Depends:R (≥ 4.1)
Imports:stats, utils, gpindex (≥ 0.6.2), Matrix (≥ 1.5-0)
Suggests:data.tree, knitr, rmarkdown, sps, testthat (≥ 3.0.0),treemap
License:MIT + file LICENSE
Encoding:UTF-8
URL:https://marberts.github.io/piar/,https://github.com/marberts/piar
BugReports:https://github.com/marberts/piar/issues
LazyData:true
VignetteBuilder:knitr
Config/testthat/edition:3
RoxygenNote:7.3.2
NeedsCompilation:no
Packaged:2025-09-17 03:54:03 UTC; steve
Author:Steve MartinORCID iD [aut, cre, cph]
Maintainer:Steve Martin <marberts@protonmail.com>
Repository:CRAN
Date/Publication:2025-09-17 04:10:02 UTC

piar: Price Index Aggregation

Description

logo

Most price indexes are made with a two-step procedure, where period-over-period elementary indexes are first calculated for a collection of elementary aggregates at each point in time, and then aggregated according to a price index aggregation structure. These indexes can then be chained together to form a time series that gives the evolution of prices with respect to a fixed base period. This package contains a collection of functions that revolve around this work flow, making it easy to build standard price indexes, and implement the methods described by Balk (2008,doi:10.1017/CBO9780511720758), von der Lippe (2007,doi:10.3726/978-3-653-01120-3), and the CPI manual (2020,doi:10.5089/9781484354841.069) for bilateral price indexes.

Author(s)

Maintainer: Steve Martinmarberts@protonmail.com (ORCID) [copyright holder]

See Also

Useful links:


Extract and replace index values

Description

Methods to extract and replace index values like a matrix.

Usage

## S3 method for class 'piar_index'x[i, j, ...]## S3 replacement method for class 'piar_index'x[i, j, ...] <- value

Arguments

x

A price index, as made by, e.g.,elementary_index().

i,j

Indices for the levels and time periods of a price index. Seedetails.

...

Not currently used.

value

A numeric vector or price index. See details.

Details

The extraction method treatsx like a matrix of index values with(named) rows for each level and columns for each time period inx. Unlike a matrix, dimensions are never dropped as subscriptingx always returns an index object. This means that subscripting with amatrix is not possible, and only a "submatrix" can be extracted. Asxis not an atomic vector, subscripting with a single index likex[1]extracts all time periods for that level.

The replacement method similarly treatx like a matrix. Ifvalue isan index object with the same number of time periods asx[i, j] andit inherits from the same class asx, then the index values andpercent-change contributions ofx[i, j] are replaced with those for thecorresponding levels ofvalue. Ifvalue is not an index, then it iscoerced to a numeric vector and behaves the same as replacing values in amatrix. Note that replacing the values of an index will remove thecorresponding percent-change contributions (if any). Unlike extraction, itis possible to replace value inx using a logical matrix or a two-columnmatrix of indices.

Value

A price index that inherits from the same class asx.

See Also

Other index methods:aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

index <- as_index(matrix(1:6, 2))index["1", ]index[, 2]index[1, ] <- 1 # can be useful for doing specific imputationsindex

Aggregate elementary price indexes

Description

Aggregate elementary price indexes with a price index aggregation structure.

Usage

## S3 method for class 'chainable_piar_index'aggregate(  x,  pias,  ...,  pias2 = NULL,  na.rm = FALSE,  contrib = TRUE,  r = 1,  include_ea = TRUE,  duplicate_contrib = c("make.unique", "sum"))## S3 method for class 'direct_piar_index'aggregate(  x,  pias,  ...,  pias2 = NULL,  na.rm = FALSE,  contrib = TRUE,  r = 1,  include_ea = TRUE,  duplicate_contrib = c("make.unique", "sum"))

Arguments

x

A price index, usually made byelementary_index().

pias

A price index aggregation structure or something that can becoerced into one. This can be made withaggregation_structure().

...

Not currently used.

pias2

An optional secondary aggregation structure, usually withcurrent-period weights, to make a superlative index. See details.

na.rm

Should missing values be removed? By default, missing valuesare not removed. Settingna.rm = TRUE is equivalent to overall meanimputation.

contrib

Aggregate percent-change contributions inx (if any)?

r

Order of the generalized mean to aggregate index values. 0 for ageometric index (the default for making elementary indexes), 1 for anarithmetic index (the default for aggregating elementary indexes andaveraging indexes over subperiods), or -1 for a harmonic index (usually fora Paasche index). Other values are possible; seegpindex::generalized_mean() for details. Ifpias2 is given then theindex is aggregated with a quadratic mean of order2*r.

include_ea

Should indexes for the elementary aggregates be includedalong with the aggregated indexes? By default, all index values arereturned.

duplicate_contrib

The method to deal with duplicate productcontributions. Either 'make.unique' to treat duplicateproducts as distinct products and make their names uniquewithmake.unique() or 'sum' to add contributions for each product.

Details

Theaggregate() method loops over each time period inx and

  1. aggregates the elementary indexes withgpindex::generalized_mean(r)() for each levelofpias;

  2. aggregates percent-change contributions for each level ofpias (if there are any andcontrib = TRUE);

  3. price updates the weights inpias withgpindex::factor_weights(r)() (only forperiod-over-period elementary indexes).

The result is a collection of aggregated period-over-period indexes thatcan be chained together to get a fixed-base index whenx areperiod-over-period elementary indexes. Otherwise, whenx are fixed-baseelementary indexes, the result is a collection of aggregated fixed-base(direct) indexes.

By default, missing elementary indexes will propagate when aggregating theindex. Missing elementary indexes can be due to both missingness of thesevalues inx, and the presence of elementary aggregates inpiasthat are not part ofx. Settingna.rm = TRUE ignores missingvalues, and is equivalent to parental (or overall mean) imputation. As anaggregated price index generally cannot have missing values (for otherwiseit can't be chained over time and weights can't be price updated), anymissing values for a level ofpias are removed and recursively replacedby the value of its immediate parent.

In most cases aggregation is done with an arithmetic mean (the default), andthis is detailed in chapter 8 (pp. 190–198) of the CPI manual (2020), withanalogous details in chapter 9 of the PPI manual (2004).Aggregating with a non-arithmetic mean follows the same steps, except thatthe elementary indexes are aggregated with a mean of a different order (e.g.,harmonic for a Paasche index), and the method for price updating the weightsis slightly different. Note that, because aggregation is done with ageneralized mean, the resulting index is consistent-in-aggregation at eachpoint in time.

Aggregating percent-change contributions uses the method in chapter 9 of theCPI manual (equations 9.26 and 9.28) when aggregating with an arithmeticmean. With a non-arithmetic mean, arithmetic weights are constructed usinggpindex::transmute_weights(r, 1)() in orderto apply this method.

There may not be contributions for all prices relatives in an elementaryaggregate if the elementary indexes are built from several sources (as withmerge()). In this case the contribution fora price relative in the aggregated index will be correct, but the sum of allcontributions will not equal the change in the value of the index. This canalso happen when aggregating an already aggregated index in which missingindex values have been imputed (i.e., whenna.rm = TRUE andcontrib = FALSE).

If two aggregation structures are given then the steps above are done foreach aggregation structure, with the aggregation forpias done with ageneralized mean of orderr the aggregation forpias2 done with ageneralized mean of order-r. The resulting indexes are combined with ageometric mean to make a superlative quadratic mean of order2*r index.Percent-change contributions are combined using a generalized van IJzerendecomposition; seegpindex::nested_transmute() for details.

Value

An aggregate price index that inherits from the class ofx.

Note

For large indexes it can be much faster to turn the aggregation structureinto an aggregation matrix withas.matrix(), then aggregateelementary indexes as a matrix operation when there are no missingvalues. See the examples for details.

References

Balk, B. M. (2008).Price and Quantity Index Numbers.Cambridge University Press.

ILO, IMF, UNECE, OECD, and World Bank. (2004).Producer Price Index Manual: Theory and Practice.International Monetary Fund.

IMF, ILO, OECD, Eurostat, UNECE, and World Bank. (2020).Consumer Price Index Manual: Concepts and Methods.International Monetary Fund.

von der Lippe, P. (2007).Index Theory and Price Statistics. Peter Lang.

See Also

Other index methods:[.piar_index(),as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

prices <- data.frame(  rel = 1:8,  period = rep(1:2, each = 4),  ea = rep(letters[1:2], 4))# A two-level aggregation structurepias <- aggregation_structure(  list(c("top", "top", "top"), c("a", "b", "c")),  weights = 1:3)# Calculate Jevons elementary indexes(elementary <- elementary_index(prices, rel ~ period + ea))# Aggregate (note the imputation for elementary index 'c')(index <- aggregate(elementary, pias, na.rm = TRUE))# Aggregation can equivalently be done as matrix multiplicationas.matrix(pias) %*% as.matrix(chain(index[letters[1:3]]))

Make a price index aggregation structure

Description

Create a price index aggregation structure from a hierarchicalclassification and aggregation weights that can be used to aggregateelementary indexes.

Usage

aggregation_structure(x, weights = NULL)

Arguments

x

A list of character vectors that give the codes/labels for eachlevel of the classification, ordered so that moving down the list goes downthe hierarchy. The last vector gives the elementary aggregates, whichshould have no duplicates. All vectors should be the same length, withoutNAs, and there should be no duplicates across different levels ofx. Names forx are used as level names; otherwise, levels are named'level1', 'level2', ..., 'ea'.

weights

A numeric vector of aggregation weights for the elementaryaggregates (i.e., the last vector inx), or something that can be coercedinto one. The default is to give each elementary aggregate the same weight.

Value

A price index aggregation structure of classpiar_aggregation_structure.This is a list-S3 class with the following components.

child

A nested list that gives the positions of the immediatechildren for each node in each level of the aggregation structure above theterminal nodes.

parent

A list that gives the position of theimmediate parent for each node of the aggregation structure below theinitial nodes.

levels

A named list of character vectors that give the levels ofx.

weights

A vector giving the weight for each elementaryaggregate.

Warning

Theaggregation_structure() function does its bestto check its arguments, but there should be no expectation that the resultofaggregation_structure() will make any sense ifx does notrepresent a nested hierarchy.

See Also

aggregate() to aggregate price indexes madewithelementary_index().

expand_classification() to makex from a characterrepresentation of a hierarchical aggregation structure.

as_aggregation_structure() to coerce tabular data into anaggregation structure.

as.data.frame() andas.matrix() to coerce anaggregation structure into a tabular form.

weights() to get theweights for an aggregation structure.

update() for updating aprice index aggregation structure with an aggregated index.

Examples

# A simple aggregation structure#            1#      |-----+-----|#      11          12#  |---+---|       |#  111     112     121#  (1)     (3)     (4)aggregation_weights <- data.frame(  level1 = c("1", "1", "1"),  level2 = c("11", "11", "12"),  ea     = c("111", "112", "121"),  weight = c(1, 3, 4))aggregation_structure(  aggregation_weights[1:3],  weights = aggregation_weights[[4]])# The aggregation structure can also be made by expanding the# elementary aggregateswith(  aggregation_weights,  aggregation_structure(expand_classification(ea), weight))

Coerce an index into a tabular form

Description

Turn an index into a data frame or a matrix.

Usage

## S3 method for class 'piar_index'as.data.frame(  x,  row.names = NULL,  optional = FALSE,  ...,  contrib = FALSE,  stringsAsFactors = FALSE)## S3 method for class 'piar_index'as.matrix(x, ...)

Arguments

x

A price index, as made by, e.g.,elementary_index().

row.names,stringsAsFactors

Seeas.data.frame().

optional

Not currently used.

...

Not currently used.

contrib

Include percent-change contributions (the default does notinclude them).

Value

as.data.frame() returns the index values inx as a data frame with threecolumns:period,level, andvalue. Ifcontrib = TRUE then there isa fourth (list) columncontrib containing percent-change contributions.

as.matrix() returns the index values inx as a matrix with a row foreach level and a column for each time period inx.

See Also

as_index() to coerce a matrix/data frame of index values into an indexobject.

Other index methods:[.piar_index(),aggregate.piar_index,as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

index <- as_index(matrix(1:6, 2))as.data.frame(index)as.matrix(index)

Coerce an aggregation structure into a tabular form

Description

Coerce a price index aggregation structure into an aggregation matrix, or adata frame.

Usage

## S3 method for class 'piar_aggregation_structure'as.matrix(x, ..., sparse = FALSE)## S3 method for class 'piar_aggregation_structure'as.data.frame(x, row.names = NULL, optional = FALSE, ...)

Arguments

x

A price index aggregation structure, as made byaggregation_structure().

...

Not currently used for the matrix method. Extra arguments toas.data.frame.list() for the data frame method.

sparse

Should the result be a sparse matrix fromMatrix? Thisis faster for large aggregation structures. The default returns an ordinarydense matrix.

row.names

Seeas.data.frame().

optional

Not currently used.

Value

as.matrix() represents an aggregation structure as a matrix,such that multiplying with a (column) vector of elementary indexes gives theaggregated index.

as.data.frame() takes an aggregation structure and returns a dataframe that could have generated it.

See Also

as_aggregation_structure() for coercing into an aggregation structure.

treemap::treemap() anddata.tree::as.Node() for visualizing anaggregation structure.

Other aggregation structure methods:cut.piar_aggregation_structure(),levels.piar_aggregation_structure(),update.piar_aggregation_structure(),weights.piar_aggregation_structure()

Examples

# A simple aggregation structure#            1#      |-----+-----|#      11          12#  |---+---|       |#  111     112     121#  (1)     (3)     (4)aggregation_weights <- data.frame(  level1 = c("1", "1", "1"),  level2 = c("11", "11", "12"),  ea     = c("111", "112", "121"),  weight = c(1, 3, 4))pias <- as_aggregation_structure(aggregation_weights)as.matrix(pias)all.equal(as.data.frame(pias), aggregation_weights)## Not run: # Visualize as a treemap.treemap::treemap(  aggregation_weights,  index = names(aggregation_weights)[-4],  vSize = "weight",  title = "aggregation structure")# Or turn into a more genereal tree object and plot.aggregation_weights$pathString <- do.call(  \(...) paste(..., sep = "/"),  aggregation_weights[-4])plot(data.tree::as.Node(aggregation_weights))## End(Not run)

Coerce an index into a time series

Description

Turn an index into a regular time series, represented as ats object.

Usage

## S3 method for class 'piar_index'as.ts(x, ...)

Arguments

x

A price index, as made by, e.g.,elementary_index().

...

Additional arguments passed tots().

Value

A time series object.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

as.ts(as_index(matrix(1:9, 3)))

Coerce to an aggregation structure

Description

Coerce an object into an aggregation structure object.

Usage

as_aggregation_structure(x, ...)## Default S3 method:as_aggregation_structure(x, ..., weights = NULL)## S3 method for class 'data.frame'as_aggregation_structure(x, ...)## S3 method for class 'matrix'as_aggregation_structure(x, ...)

Arguments

x

An object to coerce into an aggregation structure.

...

Further arguments passed to or used by methods.

weights

A numeric vector of aggregation weights for the elementaryaggregates. The default is to give each elementary aggregate the sameweight.

Details

The default method attempts to coercex into a list prior to callingaggregation_structure().

The data frame and matrix methods treatx as a table with a row foreach elementary aggregate, a column of labels for each level in theaggregation structure, and a column of weights for the elementary aggregates.

Value

A price index aggregation structure that inherits frompiar_aggregation_structure.

See Also

as.matrix() andas.data.frame() forcoercing an aggregation structure into a tabular form.

Examples

# A simple aggregation structure#            1#      |-----+-----|#      11          12#  |---+---|       |#  111     112     121#  (1)     (3)     (4)aggregation_weights <- data.frame(  level1 = c("1", "1", "1"),  level2 = c("11", "11", "12"),  ea     = c("111", "112", "121"),  weight = c(1, 3, 4))pias <- aggregation_structure(  aggregation_weights[1:3],  weights = aggregation_weights[[4]])all.equal(  pias,  as_aggregation_structure(aggregation_weights))all.equal(  pias,  as_aggregation_structure(as.matrix(aggregation_weights)))

Coerce to a price index

Description

Coerce pre-computed index values into an index object.

Usage

as_index(x, ...)## Default S3 method:as_index(x, ...)## S3 method for class 'matrix'as_index(x, ..., chainable = TRUE, contrib = FALSE)## S3 method for class 'data.frame'as_index(x, ..., contrib = FALSE)## S3 method for class 'chainable_piar_index'as_index(x, ..., chainable = TRUE)## S3 method for class 'direct_piar_index'as_index(x, ..., chainable = FALSE)## S3 method for class 'mts'as_index(x, ...)

Arguments

x

An object to coerce into a price index.

...

Further arguments passed to or used by methods.

chainable

Are the index values inx period-over-periodindexes, suitable for a chained calculation (the default)? This should beFALSE whenx contains fixed-base (direct) index values.

contrib

Should the index values inx be used to constructpercent-change contributions? The default does not make contributions.

Details

Numeric matrices are coerced into an index object by treating each column asa separate time period, and each row as a separate level of the index (e.g.,an elementary aggregate). Column namesare used to denote time periods, and row names are used to denote levels(so they must be unique). This essentially reverses callingas.matrix() on an index object. If adimension is unnamed, then it is given a sequential label from 1 to the sizeof that dimension. The default and multiple time series methods coercesxto a matrix prior to using the matrix method.

The data frame method foras_index() is best understood as reversingthe effect ofas.data.frame() on anindex object. It constructs a matrix by taking the levels ofx[[1]] as columns and the levels ofx[[2]] as rows(coercing to a factor if necessary). It then populates this matrix with thecorresponding values inx[[3]], and uses the matrix method foras_index(). Ifcontrib = TRUE and there is a fourth list column ofproduct contributions then these are also included in the resulting index.

Ifx is a period-over-period index then it is returned unchanged whenchainable = TRUE and chained otherwise. Similarly, ifx is afixed-base index then it is returned unchanged whenchainable = FALSE and unchain otherwise.

Value

A price index that inherits frompiar_index. Ifchainable = TRUE then this is aperiod-over-period price index that also inherits fromchainable_piar_index; otherwise, it is a fixed-base index thatinherits fromdirect_piar_index.

See Also

as.matrix() andas.data.frame() for coercing an indexinto a tabular form.

Examples

prices <- data.frame(  rel = 1:8,  period = rep(1:2, each = 4),  ea = rep(letters[1:2], 4))index <- elementary_index(prices, rel ~ period + ea)all.equal(as_index(as.data.frame(index)), index)all.equal(as_index(as.matrix(index)), index)

Chain and rebase a price index

Description

Chain a period-over-period index by taking the cumulative product of itsvalues to turn it into a fixed-base (direct) index.

Unchain a fixed-base index by dividing its values for successive periods toget a period-over-period index.

Rebase a fixed-base index by dividing its values with the value of the indexin the new base period.

Usage

chain(x, ...)## Default S3 method:chain(x, ...)## S3 method for class 'chainable_piar_index'chain(x, link = rep(1, nlevels(x)), ...)unchain(x, ...)## Default S3 method:unchain(x, ...)## S3 method for class 'direct_piar_index'unchain(x, base = rep(1, nlevels(x)), ...)rebase(x, ...)## Default S3 method:rebase(x, ...)## S3 method for class 'direct_piar_index'rebase(x, base = rep(1, nlevels(x)), ...)

Arguments

x

A price index, as made by, e.g.,elementary_index().

...

Further arguments passed to or used by methods.

link

A numeric vector, or something that can coerced into one, oflink values for each level inx. The default is a vector of 1s sothat no linking is done.

base

A numeric vector, or something that can coerced into one, ofbase-period index values for each level inx. The default is a vectorof 1s so that the base period remains the same. Ifbase is a length-onecharacter vector giving a time period ofx then the index values for thistime period are used as the base-period values.

Details

The default methods attempt to coercex into an index withas_index() prior to chaining/unchaining/rebasing.

Chaining an index takes the cumulative product of the index values for eachlevel; this is roughly the same ast(apply(as.matrix(x), 1, cumprod)) * link. Unchaining does the opposite,so these are inverse operations. Note that unchaining a period-over-periodindex does nothing, as does chaining a fixed-base index.

Rebasing a fixed-base index divides the values for each level of this indexby the corresponding values for each level in the new base period. It'sroughly the same asas.matrix(x) / base. Like unchaining, rebasing aperiod-over-period index does nothing.

Percent-change contributions are removed when chaining/unchaining/rebasingan index as it's not usually possible to update them correctly.

Value

chain() andrebase() return a fixed-base index that inheritsfromdirect_piar_index.

unchain() returns a period-over-period index that inherits fromchainable_piar_index.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

index <- as_index(matrix(1:9, 3))# Make period 0 the fixed base periodchain(index)# Chaining and unchaining reverse each otherall.equal(index, unchain(chain(index)))# Change the base period to period 2 (note the# loss of information for period 0)index <- chain(index)rebase(index, index[, 2])

Extract percent-change contributions

Description

Extract a matrix or data frame of percent-change contributions from a priceindex.

Usage

contrib(x, ...)## S3 method for class 'piar_index'contrib(x, level = levels(x)[1L], period = time(x), ..., pad = 0)contrib2DF(x, ...)## S3 method for class 'piar_index'contrib2DF(x, level = levels(x)[1L], period = time(x), ...)contrib(x, ...) <- value## S3 replacement method for class 'piar_index'contrib(x, level = levels(x)[1L], period = time(x), ...) <- valueset_contrib(x, ..., value)set_contrib_from_index(x)

Arguments

x

A price index, as made by, e.g.,elementary_index().

...

Further arguments passed to or used by methods.

level

The level of an index for which percent-change contributionsare desired, defaulting to the first level (usually the top-level for anaggregate index).contrib2DF() can accept multiple levels.

period

The time periods for which percent-change contributions aredesired, defaulting to all time periods.

pad

A numeric value to pad contributions so that they fit into arectangular array when products differ over time. The default is 0.

value

A numeric matrix of replacement contributions with a row foreach product and a column for each time period. Recycling occurs along timeperiods.

Value

contrib() returns a matrix of percent-change contributions with a columnfor eachperiod and a row for each product (sorted) for which there arecontributions inlevel. Contributions are padded withpad to fit into arectangular array when products differ over time. The replacement methodsreturns a copy ofx with contributions given by the matrixvalue.(set_contrib() is an alias that's easier to use with pipes.)set_contrib_from_index() is a helper to return a copy ofx with allcontributions set to the corresponding index value minus 1.

contrib2DF() returns a data frame of contributions with fourcolumns:period,level,product, andvalue.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

prices <- data.frame(  rel = 1:8,  period = rep(1:2, each = 4),  ea = rep(letters[1:2], 4))index <- elementary_index(prices, rel ~ period + ea, contrib = TRUE)pias <- aggregation_structure(  list(c("top", "top", "top"), c("a", "b", "c")),  weights = 1:3)index <- aggregate(index, pias, na.rm = TRUE)# Percent-change contributions for the top-level indexcontrib(index)contrib2DF(index)# Calculate EA contributions for the chained indexlibrary(gpindex)arithmetic_contributions(  as.matrix(chain(index))[c("a", "b", "c"), 2],  weights(pias))

Cut an aggregation structure

Description

Keep only the part of an aggregation structure above or below a certainlevel.

Usage

## S3 method for class 'piar_aggregation_structure'cut(x, level, ..., na.rm = FALSE, upper = TRUE)

Arguments

x

A price index aggregation structure, as made byaggregation_structure().

level

A positive integer, or something that can be coerced into one,giving the level at which to cutx.

...

Not currently used.

na.rm

Should missing values be removed when aggregating theweights? By default, missing values are not removed.

upper

Keep only the part ofx abovelevel (the default);otherwise, return the part ofx belowlevel.

Value

A price index aggregation structure.

See Also

Other aggregation structure methods:as.matrix.piar_aggregation_structure(),levels.piar_aggregation_structure(),update.piar_aggregation_structure(),weights.piar_aggregation_structure()

Examples

# A simple aggregation structure#            1#      |-----+-----|#      11          12#  |---+---|       |#  111     112     121#  (1)     (3)     (4)aggregation_weights <- data.frame(  level1 = c("1", "1", "1"),  level2 = c("11", "11", "12"),  ea     = c("111", "112", "121"),  weight = c(1, 3, 4))pias <- aggregation_structure(  aggregation_weights[1:3],  weights = aggregation_weights[[4]])# Turn it into#            1#      |-----+-----|#      11          12#     (4)         (4)cut(pias, 2)

Make elementary/elemental price indexes

Description

Compute period-over-period (chainable) or fixed-base (direct) elementaryprice indexes, with optional percent-change contributions for eachproduct.

Usage

elementary_index(x, ...)## Default S3 method:elementary_index(x, ...)## S3 method for class 'numeric'elementary_index(  x,  ...,  period = gl(1, length(x)),  ea = gl(1, length(x)),  weights = NULL,  product = NULL,  chainable = TRUE,  na.rm = FALSE,  contrib = FALSE,  r = 0)## S3 method for class 'data.frame'elementary_index(x, formula, ..., weights = NULL, product = NULL)elemental_index(x, ...)

Arguments

x

Period-over-period or fixed-base price relatives. Currently thereare methods for numeric vectors (which can be made withprice_relative()) and data frames.

...

Further arguments passed to or used by methods.

period

A factor, or something that can be coerced into one, givingthe time period associated with each price relative inx. Theordering of time periods follows of the levels ofperiod, to agreewithcut(). The default makes an index for one time period.

ea

A factor, or something that can be coerced into one, giving theelementary aggregate associated with each price relative inx. Thedefault makes an index for one elementary aggregate.

weights

A numeric vector of weights for the price relatives inx,or something that can be coerced into one. The default is equal weights.This is evaluated inx for the data frame method.

product

A character vector of product names, or something that canbe coerced into one, for each price relative inx when makingpercent-change contributions. The default uses the names ofx, if any;otherwise, elements ofx are given sequential names within eachelementary aggregate. This is evaluated inx for the data frame method.

chainable

Are the price relatives inx period-over-periodrelatives that are suitable for a chained calculation (the default)? Thisshould beFALSE whenx contains fixed-base relatives.

na.rm

Should missing values be removed? By default, missing valuesare not removed. Settingna.rm = TRUE is equivalent to overall meanimputation.

contrib

Should percent-change contributions be calculated? Thedefault does not calculate contributions.

r

Order of the generalized mean to aggregate price relatives. 0 for ageometric index (the default for making elementary indexes), 1 for anarithmetic index (the default for aggregating elementary indexes andaveraging indexes over subperiods), or -1 for a harmonic index (usually fora Paasche index). Other values are possible; seegpindex::generalized_mean() for details.

formula

A two-sided formula with price relatives on the left-handside, and time periods and elementary aggregates (in that order) on theright-hand side.

Details

When supplied with a numeric vector,elementary_index() is a simplewrapper that appliesgpindex::generalized_mean(r)() andgpindex::contributions(r)() (ifcontrib = TRUE)tox andweights grouped byea andperiod. Thatis, for every combination of elementary aggregate and time period,elementary_index() calculates an index based on a generalized mean oforderr and, optionally, percent-change contributions. Product names shouldbe unique within each time period when making contributions, and, if not, arepassed tomake.unique() with a warning. The default(r = 0 and no weights) makes Jevons elementary indexes. See chapter 8(pp. 175–190) of the CPI manual (2020) for more detail about makingelementary indexes, or chapter 9 of the PPI manual (2004), and chapter 5 ofBalk (2008).

The default method simply coercesx to a numeric vector prior tocalling the method above. The data frame method provides a formula interfaceto specify columns of price relatives, time periods, and elementaryaggregates and call the method above.

The interpretation of the index depends on how the price relatives inx are made. If these are period-over-period relatives, then theresult is a collection of period-over-period (chainable) elementary indexes;if these are fixed-base relatives, then the result is a collection offixed-base (direct) elementary indexes. For the latter,chainableshould be set toFALSE so that no subsequent methods assume that achained calculation should be used.

By default, missing price relatives inx will propagate throughoutthe index calculation. Ignoring missing values withna.rm = TRUE isthe same as overall mean (parental) imputation, and needs to be explicitlyset in the call toelementary_index(). Explicit imputation of missingrelatives, and especially imputation of missing prices, should be done priorto callingelementary_index().

Indexes based on nested generalized means, like the Fisher index (andsuperlative quadratic mean indexes more generally), can be calculated bysupplying the appropriate weights withgpindex::nested_transmute(); see theexample below. It is important to note that there are several ways tomake these weights, and this affects how percent-change contributionsare calculated.

elemental_index() is an alias forelementary_index().

Value

A price index that inherits frompiar_index. Ifchainable = TRUE then this is a period-over-period index that alsoinherits fromchainable_piar_index; otherwise, it is afixed-based index that inherits fromdirect_piar_index.

References

Balk, B. M. (2008).Price and Quantity Index Numbers.Cambridge University Press.

ILO, IMF, UNECE, OECD, and World Bank. (2004).Producer Price Index Manual: Theory and Practice.International Monetary Fund.

IMF, ILO, OECD, Eurostat, UNECE, and World Bank. (2020).Consumer Price Index Manual: Concepts and Methods.International Monetary Fund.

von der Lippe, P. (2007).Index Theory and Price Statistics. Peter Lang.

See Also

price_relative() for making price relatives for the same products overtime, andcarry_forward() andshadow_price() forimputation of missing prices.

as_index() to turn pre-computed (elementary) index values into anindex object.

chain() for chaining period-over-period indexes, andrebase() for rebasing an index.

aggregate() to aggregate elementary indexesaccording to an aggregation structure.

as.matrix() andas.data.frame() for coercing an indexinto a tabular form.

Examples

library(gpindex)prices <- data.frame(  rel = 1:8,  period = rep(1:2, each = 4),  ea = rep(letters[1:2], 4))# Calculate Jevons elementary indexeselementary_index(prices, rel ~ period + ea)# Same as using lm() or tapply()exp(coef(lm(log(rel) ~ ea:factor(period) - 1, prices)))with(  prices,  t(tapply(rel, list(period, ea), geometric_mean, na.rm = TRUE)))# A general function to calculate weights to turn the geometric# mean of the arithmetic and harmonic mean (i.e., Fisher mean)# into an arithmetic meanfw <- grouped(nested_transmute(0, c(1, -1), 1))# Calculate a CSWD index (same as the Jevons in this example)# as an arithmetic index by using the appropriate weightselementary_index(  prices,  rel ~ period + ea,  weights = fw(rel, group = interaction(period, ea)),  r = 1)

Expand a hierarchical classification

Description

Expand a character representation of a hierarchical classification to make aprice index aggregation structure. Expanded classifications be interactedtogether to get all combinations of aggregation structures.

Usage

expand_classification(x, width = 1L, pad = NA)interact_classifications(..., sep = ":")

Arguments

x

A character vector, or something that can be coerced into one, ofcodes/labels for a specific level in a classification (e.g., 5-digitCOICOP, 5-digit NAICS, 4-digit SIC).

width

An integer vector that gives the width of each digit inx. A single value is recycled to span the longest element inx. This cannot contain NAs. The default assumes each digit has awidth of 1, as in the NAICS, NAPCS, and SIC classifications.

pad

A string used to pad the shorter labels for an unbalancedclassification. The default pads with NA.

...

Lists of character vectors that give the codes/labels for eachlevel of the classification, ordered so that moving down the list goes downthe hierarchy (as made byexpand_classification()).

sep

A character used to combine codes/labels across elements of....The default uses ':'.

Value

expand_classification() returns a list with a entry for each levelinx giving the "digits" that represent each level in the hierarchy.

interact_classfications() returns a list of lists with the same structureasexpand_classification().

See Also

aggregation_structure() to make a price-index aggregation structure.

split_classification() to expand a classification by splitting alonga delimiter.

csh_from_digits() in theaccumulate package for different handlingof unbalanced classifications.

Examples

# A simple classification structure#            1#      |-----+-----|#      11          12#  |---+---|       |#  111     112     121expand_classification(c("111", "112", "121"))# Expanding more complex classifications# ... if last 'digit' is either TA or TSexpand_classification(  c("111TA", "112TA", "121TS"),  width = c(1, 1, 1, 2))# ... if first 'digit' is either 11 or 12expand_classification(c("111", "112", "121"), width = c(2, 1))# ...if there are delimiters in the classification (like COICOP)expand_classification(c("01.1.1", "01.1.2", "01.2.1"), width = 2)

Return the first/last parts of an index

Description

Extract the first/last parts of an index as if it were a matrix.

Usage

## S3 method for class 'piar_index'head(x, n = 6L, ...)## S3 method for class 'piar_index'tail(x, n = 6L, ...)

Arguments

x

A price index, as made by, e.g.,elementary_index().

n

Seehead()/tail(). The default takes thefirst/last 6 levels ofx.

...

Not currently used.

Value

A price index that inherits from the same class asx.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

index <- as_index(matrix(1:9, 3))head(index, 1)tail(index, 1)

Impute missing prices

Description

Impute missing prices using the carry forward or shadow price method.

Usage

shadow_price(x, ...)## Default S3 method:shadow_price(  x,  ...,  period,  product,  ea,  pias = NULL,  weights = NULL,  r1 = 0,  r2 = 1)## S3 method for class 'data.frame'shadow_price(x, formula, ..., weights = NULL)carry_forward(x, ...)## Default S3 method:carry_forward(x, ..., period, product)## S3 method for class 'data.frame'carry_forward(x, formula, ...)carry_backward(x, ...)## Default S3 method:carry_backward(x, ..., period, product)## S3 method for class 'data.frame'carry_backward(x, formula, ...)

Arguments

x

Either a numeric vector (or something that can be coerced into one)or data frame of prices.

...

Further arguments passed to or used by methods.

period

A factor, or something that can be coerced into one, givingthe time period associated with each price inx. The ordering of timeperiods follows of the levels ofperiod, to agree withcut().

product

A factor, or something that can be coerced into one, givingthe product associated with each price inx.

ea

A factor, or something that can be coerced into one, giving theelementary aggregate associated with each price inx.

pias

A price index aggregation structure, or something that can becoerced into one, as made withaggregation_structure(). The defaultimputes from elementary indexes only (i.e., not recursively).

weights

A numeric vector of weights for the prices inx (i.e.,product weights), or something that can be coerced into one. The default isto give each price equal weight. This is evaluated inx for the dataframe method.

r1

Order of the generalized-mean price index used to calculate theelementary price indexes: 0 for a geometric index (the default), 1 for anarithmetic index, or -1 for a harmonic index. Other values are possible;seegpindex::generalized_mean() for details.

r2

Order of the generalized-mean price index used to aggregate theelementary price indexes: 0 for a geometric index, 1 for an arithmeticindex (the default), or -1 for a harmonic index. Other values are possible;seegpindex::generalized_mean() for details.

formula

A two-sided formula with prices on the left-handside. Forcarry_forward() andcarry_backward(), the right-hand sideshould have time periods and products (in that order); forshadow_price(), the right-hand side should have time period, products,and elementary aggregates (in that order).

Details

The carry forward method replaces a missing price for a product by the pricefor the same product in the previous period. It tends to push an index valuetowards 1, and is usually avoided; see paragraph 6.61 in the CPI manual(2020). The carry backwards method does the opposite, but this is rarelyused in practice.

The shadow price method recursively imputes a missing price by the value ofthe price for the same product in the previous period multiplied by thevalue of the period-over-period elementary index for the elementary aggregateto which that product belongs. This requires computing and aggregating anindex (according topias, unlesspias is not supplied) foreachperiod, and so these imputations can take a while. The indexvalues used to do the imputations are not returned because the index needsto be recalculated to get correct percent-change contributions.

Shadow price imputation is referred to as self-correcting overall meanimputation in chapter 6 of the CPI manual (2020). It is identical to simplyexcluding missing price relatives in the index calculation, except in theperiod that a missing product returns. For this reason care is needed whenusing this method. It is sensitive to the assumption that a product does notchange over time, and in some cases it is safer to simply omit the missingprice relatives instead of imputing the missing prices.

Value

A numeric vector of prices with missing values replaced (where possible).

References

IMF, ILO, OECD, Eurostat, UNECE, and World Bank. (2020).Consumer Price Index Manual: Concepts and Methods.International Monetary Fund.

See Also

price_relative() for making price relatives for thesame products over time.

Examples

prices <- data.frame(  price = c(1:7, NA),  period = rep(1:2, each = 4),  product = 1:4,  ea = rep(letters[1:2], 4))carry_forward(prices, price ~ period + product)shadow_price(prices, price ~ period + product + ea)

Missing values in a price index

Description

Identify missing values in a price index.

Usage

## S3 method for class 'piar_index'is.na(x)## S3 method for class 'piar_index'anyNA(x, recursive = FALSE)

Arguments

x

A price index, as made by, e.g.,elementary_index().

recursive

Check ifx also has missing percent-changecontributions. By default only index values are checked for missingness.

Value

is.na() returns a logical matrix, with a row for each level ofx and acolumns for each time period, that indicates which index values are missing.

anyNA() returnsTRUE if any index values are missing, or percent-changecontributions (ifrecursive = TRUE).

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

index <- as_index(matrix(c(1, 2, 3, NA, 5, NA), 2))anyNA(index)is.na(index)# Carry forward imputationindex[is.na(index)] <- 1index

Test if an object is an aggregation structure

Description

Test if an object is a price index aggregation structure.

Usage

is_aggregation_structure(x)

Arguments

x

An object to test.

Value

ReturnsTRUE ifx inherits frompiar_aggregation_structure.


Test if an object is a price index

Description

Test if an object is a index object or a subclass of an index object.

Usage

is_index(x)is_chainable_index(x)is_direct_index(x)

Arguments

x

An object to test.

Value

is_index() returnsTRUE ifx inherits frompiar_index.

is_chainable_index() returnsTRUE ifx inherits fromchainable_piar_index.

is_direct_index() returnsTRUE ifx inherits fromdirect_piar_index.


Get the levels for an aggregation structure

Description

Get the hierarchical list of levels for an aggregation structure. It isan error to try and replace these values.

Usage

## S3 method for class 'piar_aggregation_structure'levels(x)

Arguments

x

A price index aggregation structure, as made byaggregation_structure().

Value

A list of character vectors giving the levels for each position in theaggregation structure.

See Also

Other aggregation structure methods:as.matrix.piar_aggregation_structure(),cut.piar_aggregation_structure(),update.piar_aggregation_structure(),weights.piar_aggregation_structure()


Get the levels for a price index

Description

Methods to get and set the levels for a price index.

Usage

## S3 method for class 'piar_index'levels(x)## S3 replacement method for class 'piar_index'levels(x) <- valueset_levels(x, value)

Arguments

x

A price index, as made by, e.g.,elementary_index().

value

A character vector, or something that can be coerced into one,giving the replacement levels forx.

Value

levels() returns a character vector with the levels for a price index.

The replacement method returns a copy ofx with the levels invalue.(set_levels() is an alias that's easier to use with pipes.)

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()


Aggregate a price index over subperiods

Description

Aggregate an index over subperiods by taking the (usually arithmetic) meanof index values over consecutive windows of subperiods.

Usage

## S3 method for class 'chainable_piar_index'mean(  x,  ...,  weights = NULL,  window = ntime(x),  na.rm = FALSE,  contrib = TRUE,  r = 1,  duplicate_contrib = c("make.unique", "sum"))## S3 method for class 'direct_piar_index'mean(  x,  ...,  weights = NULL,  window = ntime(x),  na.rm = FALSE,  contrib = TRUE,  r = 1,  duplicate_contrib = c("make.unique", "sum"))

Arguments

x

A price index, as made by, e.g.,elementary_index().

...

Not currently used.

weights

A numeric vector of weights for the index values inx, orsomething that can be coerced into one. Thedefault is equal weights. It is usually easiest to specify these weights asa matrix with a row for each index value inx and a column for eachtime period.

window

A positive integer giving the size of the window used toaverage index values across subperiods. The default averages over allperiods inx. Non-integers are truncated towards 0.

na.rm

Should missing values be removed? By default, missing valuesare not removed. Settingna.rm = TRUE is equivalent to overall meanimputation.

contrib

Aggregate percent-change contributions inx (if any)?

r

Order of the generalized mean to aggregate index values. 0 for ageometric index (the default for making elementary indexes), 1 for anarithmetic index (the default for aggregating elementary indexes andaveraging indexes over subperiods), or -1 for a harmonic index (usually fora Paasche index). Other values are possible; seegpindex::generalized_mean() for details.

duplicate_contrib

The method to deal with duplicate productcontributions. Either 'make.unique' to make duplicate product names uniquewithmake.unique() or 'sum' to add contributions for the same productsacross subperiods.

Details

Themean() method constructs a set of non-overlapping windows oflengthwindow, starting in the first period of the index, and takesthe mean of each index value in these windows for each level of the index.The last window is discarded if it is incomplete (with a warning), so thatindex values arealways averaged overwindow periods. The names for the first timeperiod in each window form the new names for the aggregated time periods.

Percent-change contributions are aggregated ifcontrib = TRUE following thesame approach asaggregate().

An optional vector of weights can be specified when aggregating index valuesover subperiods, which is often useful when aggregating a Paasche index; seesection 4.3 of Balk (2008) for details.

Value

A price index, averaged over subperiods, that inherits from the sameclass asx.

References

Balk, B. M. (2008).Price and Quantity Index Numbers.Cambridge University Press.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

index <- as_index(matrix(c(1:12, 12:1), 2, byrow = TRUE), chainable = FALSE)# Turn a monthly index into a quarterly indexmean(index, window = 3)

Merge price indexes

Description

Combine two price indexes with common time periods, merging together theindex values and percent-change contributions for each time period.

This is useful for building up an index when different elementary aggregatescome from different sources of data, or use different index-number formulas.

Usage

## S3 method for class 'chainable_piar_index'merge(x, y, ...)## S3 method for class 'direct_piar_index'merge(x, y, ...)

Arguments

x

A price index, as made by, e.g.,elementary_index().

y

A price index, or something that can coerced into one. Ifxis a period-over-period index theny is coerced into a chainableindex; otherwise,y is coerced into a direct index.

...

Not currently used.

Value

A combined price index that inherits from the same class asx.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,split.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

index1 <- as_index(matrix(1:6, 2))index2 <- index1levels(index2) <- 3:4merge(index1, index2)

Price index objects

Description

There are several classes to represent price indexes.

Details

Thepiar_index object is a list-S3 class with the followingcomponents:

index

A list with an entry for each period intime that givesa vector of index values for each level inlevels.

contrib

A list with an entry for each period intime, whichitself contains a list with an entry for each level inlevels witha named vector that gives the percent-change contribution for each pricerelative.

levels

A character vector giving the levels of the index.

time

A character vector giving the time periods for the index.

Thechainable_piar_index anddirect_piar_index subclasses havethe same structure as thepiar_index class, but differ in the methodsused to manipulate the indexes.


Price data

Description

Sample price and weight data for both a match sample and fixed sample typeindex.


Calculate period-over-period price relatives

Description

Construct period-over-period price relatives from information on prices andproducts over time.

Usage

price_relative(x, ...)## Default S3 method:price_relative(x, ..., period, product)## S3 method for class 'data.frame'price_relative(x, formula, ...)

Arguments

x

Either a numeric vector (or something that can be coerced into one)or data frame of prices.

...

Further arguments passed to or used by methods.

period

A factor, or something that can be coerced into one, thatgives the corresponding time period for each element inx. Theordering of time periods follows the levels ofperiod to agree withcut().

product

A factor, or something that can be coerced into one, thatgives the corresponding product identifier for each element inx.

formula

A two-sided formula with prices on the left-handside, and time periods and products (in that order) on theright-hand side.

Value

A numeric vector of price relatives, withproduct as names.

See Also

gpindex::back_period() to get only the back price.

gpindex::base_period() for making fixed-base price relatives.

carry_forward() andshadow_price() to impute missing prices.

gpindex::outliers for methods to identify outliers with price relatives.

Examples

price_relative(  1:6,  period = rep(1:2, each = 3),  product = rep(letters[1:3], 2))

Split an index into groups

Description

Split an index into groups of indexes according to a factor, along eitherthe levels or time periods of the index.

Usage

## S3 method for class 'piar_index'split(x, f, drop = FALSE, ..., margin = c("levels", "time"))## S3 replacement method for class 'piar_index'split(x, f, drop = FALSE, ..., margin = c("levels", "time")) <- value

Arguments

x

A price index, as made by, e.g.,elementary_index().

f

A factor or list of factors to group elements ofx.

drop

Should levels that do not occur inf be dropped? By defaultall levels are kept.

...

Further arguments passed tosplit.default().

margin

Either 'levels' to split over the levels ofx (the default),or 'time' to split over the time periods ofx.

value

A list of values compatible with the splitting ofx, orsomething that can be coerced into one, recycled if necessary.

Value

split() returns a list of index objects for each level inf. Thereplacement method replaces these values with the corresponding element ofvalue.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),stack.piar_index(),time.piar_index(),window.piar_index()

Examples

index <- as_index(matrix(1:6, 2))split(index, 1:2)split(index, c(1, 1, 2), margin = "time")

Split a hierarchical classification

Description

Expand a character representation of a hierarchical classification to make aprice index aggregation structure by splitting along a delimiter.

Usage

split_classification(x, split, ..., sep = ".", pad = NA)

Arguments

x

A character vector, or something that can be coerced into one, ofcodes/labels for a specific level in a classification (e.g., 5-digitCOICOP).

split

A regular expression to delineate and split the levels inx.Seestrsplit().

...

Additional argument to pass tostrsplit().

sep

A character used to delineate levels inx in the result. Thedefault separates levels by '.'.

pad

A string used to pad the shorter labels for an unbalancedclassification. The default pads with NA.

Value

A list with a entry for each level inx giving the "digits" thatrepresent each level in the hierarchy.

See Also

aggregation_structure() to make a price-index aggregation structure.

expand_classification() to expand a classification by the width of thelevels.

Examples

#' # A simple classification structure#            1#      |-----+-----|#      11          12#  |---+---|       |#  111     112     121split_classification(c("111", "112", "121"), "")# Useful if there are delimiters in the classification (like COICOP)split_classification(c("01.1.1", "01.1.2", "01.2.1"), ".", fixed = TRUE)

Stack price indexes

Description

stack() combines two price indexes with common levels, stacking indexvalues and percent-change contributions for one index after the other.

unstack() breaks up a price index into a list of indexes for eachtime period.

These methods can be used in a map-reduce to make an index with multipleaggregation structures (like a Paasche index).

Usage

## S3 method for class 'chainable_piar_index'stack(x, y, ...)## S3 method for class 'direct_piar_index'stack(x, y, ...)## S3 method for class 'chainable_piar_index'unstack(x, ...)## S3 method for class 'direct_piar_index'unstack(x, ...)

Arguments

x

A price index, as made by, e.g.,elementary_index().

y

A price index, or something that can coerced into one. Ifxis a period-over-period index theny is coerced into a chainableindex; otherwise,y is coerced into a direct index.

...

Not currently used.

Value

stack() returns a combined price index that inherits from the same classasx.

unstack() returns a list of price indexes with the same class asx.

Note

It may be necessary to userebase() prior to stacking fixed-based priceindexes to ensure they have the same base period.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),time.piar_index(),window.piar_index()

Examples

index1 <- as_index(matrix(1:6, 2))index2 <- index1time(index2) <- 4:6stack(index1, index2)# Unstack does the reverseall.equal(  c(unstack(index1), unstack(index2)),  unstack(stack(index1, index2)))

Get the time periods for a price index

Description

Methods to get and set the time periods for a price index.

Usage

## S3 method for class 'piar_index'time(x, ...)time(x) <- value## S3 replacement method for class 'piar_index'time(x) <- valueset_time(x, value)## S3 method for class 'piar_index'start(x, ...)## S3 method for class 'piar_index'end(x, ...)ntime(x)

Arguments

x

A price index, as made by, e.g.,elementary_index().

...

Not currently used.

value

A character vector, or something that can be coerced into one,giving the replacement time periods forx.

Value

time() returns a character vector with the time periods for a price index.start() andend() return the first and last time period.

ntime() returns the number of time periods, analogous tonlevels().

The replacement method returns a copy ofx with the time periods invalue. (set_time() is an alias that's easier to use with pipes.)

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),window.piar_index()


Update an aggregation structure

Description

Price update the weights in a price index aggregation structure.

Usage

## S3 method for class 'piar_aggregation_structure'update(object, index, period = end(index), ..., r = 1)

Arguments

object

A price index aggregation structure, as made byaggregation_structure().

index

A fixed-base (direct) price index, or something that can becoerced into one. Usually an aggregate price index as made byaggregate().

period

The time period used to price update the weights. The defaultuses the last period inindex.

...

Not currently used.

r

Order of the generalized mean to update the weights. The default is1 for an arithmetic index.

Value

A copy ofobject with price-updated weights using the indexvalues inindex.

See Also

aggregate() to make an aggregated price index.

Other aggregation structure methods:as.matrix.piar_aggregation_structure(),cut.piar_aggregation_structure(),levels.piar_aggregation_structure(),weights.piar_aggregation_structure()

Examples

# A simple aggregation structure#            1#      |-----+-----|#      11          12#  |---+---|       |#  111     112     121#  (1)     (3)     (4)aggregation_weights <- data.frame(  level1 = c("1", "1", "1"),  level2 = c("11", "11", "12"),  ea     = c("111", "112", "121"),  weight = c(1, 3, 4))pias <- as_aggregation_structure(aggregation_weights)index <- as_index(  matrix(1:9, 3, dimnames = list(c("111", "112", "121"), NULL)))weights(pias, ea_only = FALSE)weights(update(pias, index), ea_only = FALSE)

Get the weights for an aggregation structure

Description

Get and set the weights for a price index aggregation structure.

Usage

## S3 method for class 'piar_aggregation_structure'weights(object, ..., ea_only = TRUE, na.rm = FALSE)weights(object) <- value## S3 replacement method for class 'piar_aggregation_structure'weights(object) <- valueset_weights(object, value)

Arguments

object

A price index aggregation structure, as made byaggregation_structure().

...

Not currently used.

ea_only

Should weights be returned for only the elementary aggregates(the default)? Setting toFALSE gives the weights for the entireaggregation structure.

na.rm

Should missing values be removed when aggregating theweights (i.e., whenea_only = FALSE)? By default, missing values arenot removed.

value

A numeric vector of weights for the elementary aggregates ofobject.

Value

weights() returns a named vector of weights for the elementary aggregates.The replacement method replaces these values without changing theaggregation structure. (set_weights() is an alias that's easier to use withpipes.)

Ifea_only = FALSE then the return value is a listwith a named vector of weights for each level in the aggregation structure.

See Also

Other aggregation structure methods:as.matrix.piar_aggregation_structure(),cut.piar_aggregation_structure(),levels.piar_aggregation_structure(),update.piar_aggregation_structure()

Examples

# A simple aggregation structure#            1#      |-----+-----|#      11          12#  |---+---|       |#  111     112     121#  (1)     (3)     (4)aggregation_weights <- data.frame(  level1 = c("1", "1", "1"),  level2 = c("11", "11", "12"),  ea     = c("111", "112", "121"),  weight = c(1, 3, 4))pias <- as_aggregation_structure(aggregation_weights)# Extract the weightsweights(pias)# ... or update themweights(pias) <- 1:3weights(pias)

Index window

Description

Extract and replace index values over a window of time periods.

Usage

## S3 method for class 'piar_index'window(x, start = NULL, end = NULL, ...)## S3 replacement method for class 'piar_index'window(x, start = NULL, end = NULL, ...) <- value

Arguments

x

A price index, as made by, e.g.,elementary_index().

start

The time period to start the window. The default in the firstperiod ofx.

end

The time period to end the window. The default is the last periodofx.

...

Not currently used.

value

A numeric vector or price index.

Value

window() extracts a price index over a window of time periods thatinherits from the same class asx. The replacement method replaces thesewithvalue.

See Also

Other index methods:[.piar_index(),aggregate.piar_index,as.data.frame.piar_index(),as.ts.piar_index(),chain(),contrib(),head.piar_index(),is.na.piar_index(),levels.piar_index(),mean.piar_index,merge.piar_index(),split.piar_index(),stack.piar_index(),time.piar_index()

Examples

x <- as_index(matrix(1:9, 3))window(x, "2")window(x, "2") <- 1x

[8]ページ先頭

©2009-2025 Movatter.jp