diff --git a/R/expandMagclass.R b/R/expandMagclass.R new file mode 100644 index 00000000..a0cc766e --- /dev/null +++ b/R/expandMagclass.R @@ -0,0 +1,11 @@ +expandMagclass <- function(x, ref, fill = 0) { + r <- new.magpie( + cells_and_regions = union(getRegions(x), getRegions(ref)), + years = union(getYears(x), getYears(ref)), + names = union(getNames(x), getNames(ref)), + fill = fill, + sets = names(dimnames(ref)) + ) + r[getRegions(x), getYears(x), getNames(x)] <- x + return(r) +} diff --git a/tests/testthat/test-expandMagclass.R b/tests/testthat/test-expandMagclass.R new file mode 100644 index 00000000..28b6f971 --- /dev/null +++ b/tests/testthat/test-expandMagclass.R @@ -0,0 +1,38 @@ +test_that("expandMagclass works", { + region <- c("AAA", "BBB", "CCC") + t <- paste0("y", c(2000, 2005, 2010)) + name <- c("foo", "bar", "bazz") + + A <- new.magpie( + cells_and_regions = region, years = t, names = name, fill = 1, + sets = c("region", "t", "name") + ) + + # spatial ---- + + ## x smaller than ref ---- + B <- expandMagclass(A[region[-2], , ], A) + expect_true(all(region %in% getRegions(B))) + + ## x larger than ref ---- + expect_equal(expandMagclass(A, A[region[-2], , ]), A) + + # temporal ---- + + ## x smaller than ref ---- + B <- expandMagclass(A[, t[-2], ], A) + expect_true(all(t %in% getYears(B))) + + ## x larger than ref ---- + expect_equal(expandMagclass(x = A, ref = A[, t[-2], ]), A) + + # names ---- + + ## x smaller than ref ---- + B <- expandMagclass(A[,,name[-2]], A) + expect_true(all(name %in% getNames(B))) + + ## x larger than ref ---- + expect_equal(expandMagclass(A, A[,,name[-2]]), A) + +})