@@ -24,6 +24,7 @@ joinStringswithSlashes <- function(...) {
24
24
}
25
25
26
26
# ' Aggregate matrix from one BEA level to another by rows and columns
27
+ # ' Can handle multiple regions; maintains locations codes in row and column names
27
28
# ' Uses a matrix formula Xl %*% matrix %*% Xr where Xl is a left crosswalk to
28
29
# ' aggregate rows and Xr is a right crosswalk to align columns
29
30
# ' @param matrix A matrix
@@ -45,34 +46,45 @@ aggregateMatrix <- function (matrix, from_level, to_level, model) {
45
46
row_locs <- substr(rows ,codeLength + 1 ,nchar(rows ))
46
47
codeLength <- nchar(gsub(" /.*" , " " , cols ))
47
48
col_locs <- substr(cols ,codeLength + 1 ,nchar(cols ))
49
+ locs <- unique(c(row_locs ,col_locs ))
50
+
48
51
49
52
# Remove locations for mapping
50
- rownames(matrix ) <- gsub(" /.*" ," " ,rownames(matrix ))
51
- colnames(matrix ) <- gsub(" /.*" ," " ,colnames(matrix ))
53
+ # rownames(matrix) <- gsub("/.*","",rownames(matrix))
54
+ # colnames(matrix) <- gsub("/.*","",colnames(matrix))
52
55
53
56
# Get crosswalk for full matching between schema
54
57
cw <- unique(model $ crosswalk [, c(from_code , to_code )])
58
+ # Add 1 to indicate match
55
59
cw $ one <- 1
60
+ # Expand the crosswalk to include location codes of rows and cols in matrix
61
+ cw_locs <- cw [0 ,]
62
+ for (loc in locs ) {
63
+ cw_loc <- cw
64
+ cw_loc [,from_code ] <- paste0(cw_loc [,from_code ],loc )
65
+ cw_loc [,to_code ] <- paste0(cw_loc [,to_code ],loc )
66
+ cw_locs <- rbind(cw_locs ,cw_loc )
67
+ }
56
68
57
69
# Build row aggregation matrix
58
- row_cw <- cw [ cw [,from_code ] %in% rownames( matrix ) ,]
70
+ row_cw <- cw_locs [ cw_locs [,from_code ] %in% rows ,]
59
71
60
72
# Cast row crosswalk into a correspondence matrix of 1s
61
73
Xl <- reshape2 :: acast(row_cw ,as.formula(paste(to_code ," ~" ,from_code )),value.var = " one" , fill = 0 )
62
74
63
75
# Ordering
64
- Xl <- Xl [,rownames( matrix ) ]
65
- if (! identical(colnames(Xl ),rownames( matrix ) )) {
76
+ Xl <- Xl [,rows ]
77
+ if (! identical(colnames(Xl ),rows )) {
66
78
stop(" Left crosswalk matrix colnames do not match rownames of passed matrix." )
67
79
}
68
80
69
81
# Build col aggregation matrix
70
- col_cw <- cw [ cw [,from_code ] %in% colnames( matrix ) ,]
82
+ col_cw <- cw_loc [ cw_loc [,from_code ] %in% cols ,]
71
83
72
84
# Cast row crosswalk into a correspondence matrix of 1s
73
85
Xr <- reshape2 :: acast(col_cw ,as.formula(paste(from_code ," ~" ,to_code )),value.var = " one" , fill = 0 )
74
- Xr <- Xr [colnames( matrix ) ,]
75
- if (! identical(colnames( matrix ) , rownames(Xr ),)) {
86
+ Xr <- Xr [cols ,]
87
+ if (! identical(cols , rownames(Xr ),)) {
76
88
stop(" Column names of passed matrix do not match right crosswalk matrix row names." )
77
89
}
78
90
0 commit comments