Skip to content

Commit 737ff92

Browse files
author
WesIngwersen
committed
#342 adds location codes back matrix.
1 parent eb84e1e commit 737ff92

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

R/UtilityFunctions.R

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ joinStringswithSlashes <- function(...) {
2424
}
2525

2626
#' 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
2728
#' Uses a matrix formula Xl %*% matrix %*% Xr where Xl is a left crosswalk to
2829
#' aggregate rows and Xr is a right crosswalk to align columns
2930
#' @param matrix A matrix
@@ -45,34 +46,45 @@ aggregateMatrix <- function (matrix, from_level, to_level, model) {
4546
row_locs <- substr(rows,codeLength+1,nchar(rows))
4647
codeLength <- nchar(gsub("/.*", "", cols))
4748
col_locs <- substr(cols,codeLength+1,nchar(cols))
49+
locs <- unique(c(row_locs,col_locs))
50+
4851

4952
# 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))
5255

5356
# Get crosswalk for full matching between schema
5457
cw <- unique(model$crosswalk[, c(from_code, to_code)])
58+
#Add 1 to indicate match
5559
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+
}
5668

5769
# 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,]
5971

6072
# Cast row crosswalk into a correspondence matrix of 1s
6173
Xl <- reshape2::acast(row_cw,as.formula(paste(to_code,"~",from_code)),value.var = "one", fill = 0)
6274

6375
# Ordering
64-
Xl <- Xl[,rownames(matrix)]
65-
if(!identical(colnames(Xl),rownames(matrix))) {
76+
Xl <- Xl[,rows]
77+
if(!identical(colnames(Xl),rows)) {
6678
stop("Left crosswalk matrix colnames do not match rownames of passed matrix.")
6779
}
6880

6981
# 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,]
7183

7284
# Cast row crosswalk into a correspondence matrix of 1s
7385
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),)) {
7688
stop("Column names of passed matrix do not match right crosswalk matrix row names.")
7789
}
7890

0 commit comments

Comments
 (0)