forked from RMI-PACTA/r2dii.analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.R
63 lines (53 loc) · 1.48 KB
/
utils.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
check_no_value_is_missing <- function(data, column) {
if (anyNA(data[[column]])) {
abort(
class = "some_value_is_missing",
sprintf("Column `%s` must not contain any `NA`s.", column)
)
}
invisible(data)
}
check_unique_id <- function(data, column) {
if (sum(duplicated(data[[column]]))) {
abort(
class = "unique_ids",
sprintf("Column `%s` must not contain any duplicates.", column)
)
}
invisible(data)
}
warn_grouped <- function(data, message) {
if (dplyr::is_grouped_df(data)) warn(message)
invisible(data)
}
# Avoid dependency on purrr
walk_ <- function(.x, .f, ...) {
.f <- rlang::as_function(.f)
lapply(.x, .f, ...)
invisible(.x)
}
# Avoid dependency on purrr
modify_at_ <- function(.x, .at, .f) {
.x[[.at]] <- .f(.x[[.at]])
.x
}
# We can remove this once we depend on R >= 3.5. See ?backports::isTRUE
isTRUE <- function(x) {
is.logical(x) && length(x) == 1L && !is.na(x) && x
}
# We can remove this once we depend on R >= 3.5. See ?backports::isFALSE
isFALSE <- function(x) {
is.logical(x) && length(x) == 1L && !is.na(x) && !x
}
aggregate_ald_by_columns <- function(data, columns) {
data %>%
dplyr::group_by_at(setdiff(names(data), c("production", "emission_factor", columns))) %>%
mutate(
weight = .data$production / sum(.data$production)
) %>%
summarize(
production = sum(.data$production),
emission_factor = sum(.data$emission_factor * .data$weight / sum(.data$weight))
) %>%
ungroup()
}