-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathareUnitsIdentical.R
71 lines (67 loc) · 2.28 KB
/
areUnitsIdentical.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#' Check whether units are identical following a specified list
#'
#' @md
#' @author Oliver Richters
#' @param vec1 units to be checked against vec2, elementwise
#' @param vec2 units to be checked against vec1, elementwise
#' @return boolean
#' @export
areUnitsIdentical <- function(vec1, vec2 = NULL) {
if (is.null(vec2)) vec2 <- head(vec1, n = 1)
# add abbreviations here that are used in the units.
abbreviations <- list(
"G" = "billion ?|bn ?",
"M" = "million ?|Million ?|mio ?",
"US" = "US\\$|USD_|USD|US_",
"US05" = "US2005",
"US10" = "US2010",
"EUR" = "EUR_",
"yr" = "year",
"CO2" = "CO2e|CO2eq|CO2-equiv",
"CF4" = "CF4-equiv",
"%" = "Percentage|Percent|percent",
"cap" = "capita",
"/" = " per "
)
# only add units that actually have the same meaning, just different spelling
identicalUnits <- list(
c("\u00B0C", "\u00C2\u00B0C", "K"),
c("kcal/cap/day", "kcal/cap/d"),
c("ktU/yr", "kt U/yr"),
c("km\u00b3", "km3"),
c("mio", "mio people"),
c("Mt Nr/yr", "Tg N/yr"),
c("Mt NO2/yr", "Mt NOX/yr"),
c("unitless", "", "-", "1", "index", NA),
c("W/m2", "W/m^2"),
c("million vehicles", "million veh"),
# below, exceptionally added units that actually differ for backwards compatibility
# for 'Energy Service|Residential and Commercial|Floor Space'
c("bn m2/yr", "bn m2"),
# for 'Productivity|Yield' and subvariables
c("t DM/ha", "t DM/ha/yr", "dm t/ha"),
# for 'Water|Environmental flow violation volume'
c("km3/yr", "km3"),
c("mha per yr", "million ha/yr"),
NULL)
# function to apply abbreviations
.abbreviateUnit <- function(unit) {
for (abb in names(abbreviations)) {
unit <- gsub(abbreviations[abb], abb, unit)
}
return(unit)
}
# apply abbreviations to inputs and identicalUnits
vec1 <- .abbreviateUnit(vec1)
vec2 <- .abbreviateUnit(vec2)
identicalUnits <- lapply(identicalUnits, .abbreviateUnit)
# function to check identity
.areIdentical <- function(x, y) {
# literally identical
isTRUE(x == y) ||
# both found in the same list element of identicalUnits above
any(unlist(lapply(identicalUnits, function(units) all(c(x, y) %in% units))))
}
# check identity on vectors
return(unname(unlist(Map(Vectorize(.areIdentical), vec1, vec2))))
}