-
Notifications
You must be signed in to change notification settings - Fork 0
/
coerce-index.R
55 lines (53 loc) · 1.33 KB
/
coerce-index.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#' Coerce an index into a tabular form
#'
#' Turn an index into a data frame or a matrix.
#'
#' @param x A price index, as made by, e.g., [elemental_index()].
#' @param stringsAsFactors See [as.data.frame()].
#' @param ... Not currently used.
#'
#' @returns
#' `as.data.frame()` returns a data frame with three columns: `period`, `level`,
#' and `value`.
#'
#' `as.matrix()` returns a matrix with a row for each level and a column
#' for each time period.
#'
#' @seealso
#' [as_index()] to coerce a matrix/data frame of index values into an index
#' object.
#'
#' @examples
#' index <- as_index(matrix(1:6, 2))
#'
#' as.data.frame(index)
#'
#' as.matrix(index)
#'
#' @family index methods
#' @export
as.data.frame.piar_index <- function(x, ..., stringsAsFactors = FALSE) {
value <- unlist(x$index, use.names = FALSE)
period <- rep(x$time, each = length(x$levels))
if (stringsAsFactors) {
data.frame(period = factor(period, x$time),
level = factor(x$levels, x$levels), value
)
} else {
data.frame(period,
level = x$levels, value,
stringsAsFactors = FALSE
)
}
}
#' @rdname as.data.frame.piar_index
#' @export
as.matrix.piar_index <- function(x, ...) {
res <- do.call(cbind, x$index)
dimnames(res) <- list(x$levels, x$time)
res
}
#' @export
as.double.piar_index <- function(x, ...) {
as.double(as.matrix(x))
}