diff --git a/DESCRIPTION b/DESCRIPTION index 25039b3..f4cfb52 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -6,6 +6,7 @@ Authors@R: c( person("Fernando", "Cagua", email = "fernando.cagua@stats.govt.nz", role = c("aut", "cre")), person("David", "Hodge", email = "david.hodge@stats.govt.nz", role = c("aut")), person("Bonnie", "Farant", email = "bonnie.farant@stats.govt.nz", role = c("aut")), + person("Nestor", "Robinson", email = "nrob536@aucklanduni.ac.nz", role = c("aut")), person("Statistics New Zealand", role = c("cph"))) Description: Helper functions commonly used in Environmental Reporting at Statistics New Zealand. It includes utility functions to connect to the @@ -41,7 +42,14 @@ URL: https://statisticsnz.github.io/er.helpers, https://github.com/statisticsnz/ BugReports: https://github.com/statisticsNZ/er.helpers/issues Encoding: UTF-8 LazyData: true -RoxygenNote: 7.1.2 +RoxygenNote: 7.3.3 Suggests: testthat (>= 2.1.0), - roxygen2 (>= 6.1.1) + roxygen2 (>= 6.1.1), + knitr, + rmarkdown, + ggplot2, + tibble, + dplyr, + pkgdown +VignetteBuilder: knitr diff --git a/docs/404.html b/docs/404.html index f1279fe..19e4b93 100644 --- a/docs/404.html +++ b/docs/404.html @@ -1,66 +1,27 @@ - - -
- + + + + -We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
+We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
+Examples of behavior that contributes to a positive environment for our community include:
+Examples of unacceptable behavior include:
+Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
+Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
+This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly.
+All community leaders are obligated to respect the privacy and security of the reporter of any incident.
+Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
+Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
+Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
+Community Impact: A violation through a single incident or series of actions.
+Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
+Community Impact: A serious violation of community standards, including sustained inappropriate behavior.
+Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
+Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
+Consequence: A permanent ban from any sort of public interaction within the community.
+This Code of Conduct is adapted from the Contributor Covenant, version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
+Community Impact Guidelines were inspired by Mozilla’s code of conduct enforcement ladder.
+For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
+Developed by Fernando Cagua, David Hodge, Bonnie Farant, Nestor Robinson.
+Site built with pkgdown 2.2.0.
+Thank you for your interest in contributing to this project. These guidelines explain how to contribute code, documentation, or feedback to repositories under the Statistics NZ GitHub Organization.
+You can contribute by:
+git checkout -b feature/<short-description>
+bugfix/fix-sql-query)[git command]: "Short summary"
+Examples:
+git commit -m "Fix: corrected null handling in SQL query"
+
+git commit -m "feat: added R function for time series interpolation"
+uat or dev branch for testing and integrationmain/master (production) are only made by mainteners/owners after quality assurance testingFixes #42)README.md if your change affects usageIf you are unsure about how to contribute, please:
+Developed by Fernando Cagua, David Hodge, Bonnie Farant, Nestor Robinson.
+Site built with pkgdown 2.2.0.
+Developed by Fernando Cagua, David Hodge, Bonnie Farant, Nestor Robinson.
+Site built with pkgdown 2.2.0.
+vignettes/anomaly-and-aggregation.Rmd
+ anomaly-and-aggregation.RmdEnvironmental time series frequently contain missing values, and international standards from organisations like the World Meteorological Organisation (WMO) specify exactly how much missing data is acceptable before an aggregated value should not be reported. er.helpers provides two complementary sets of tools for these situations:
aggregate_with_criteria() returns the requested aggregate, or NA if either the total number of missing values or the length of the longest consecutive run of missing values exceeds the specified thresholds.
Thresholds can be expressed as counts (integers ≥ 1) or proportions (0 < value ≤ 1):
+
+# A month of daily temperatures with a few missing days
+# randomize sequence of daily temperatures and missing values to demonstrate consecutive-missing criteria
+set.seed(42)
+daily_temp <- sample(c(15:25, NA, NA, NA), size = 30, replace = TRUE)
+
+# Allow up to 3 missing days and no more than 2 consecutive missing days
+aggregate_with_criteria(daily_temp, max_missing = 3, max_consecutive = 2)
+#> [1] 19.62963
+
+# Tigthen the criteria: allow at most 2 missing days and no more than 1 consecutive missing day
+aggregate_with_criteria(daily_temp, max_missing = 2, max_consecutive = 1)
+#> [1] NAmean_with_criteria(), min_with_criteria(), max_with_criteria(), and sum_with_criteria() call aggregate_with_criteria() with the appropriate fun argument pre-set:
+mean_with_criteria(daily_temp, max_missing = 3, max_consecutive = 2)
+#> [1] 19.62963
+min_with_criteria(daily_temp, max_missing = 3, max_consecutive = 2)
+#> [1] 15
+max_with_criteria(daily_temp, max_missing = 3, max_consecutive = 2)
+#> [1] 25
+sum_with_criteria(daily_temp, max_missing = 3, max_consecutive = 2)
+#> [1] 530dplyr
+A common workflow is to compute a monthly aggregate from daily data:
+
+set.seed(42)
+
+daily_data <- tibble(
+ date = seq.Date(as.Date("2020-01-01"),
+ as.Date("2020-12-31"), by = "day"),
+ temperature = runif(366, min = 5, max = 25)) |>
+ # Introduce ~8 % random missing values
+ mutate(temperature = ifelse(runif(n()) < 0.08, NA, temperature))
+
+monthly_means <- daily_data |>
+ mutate(year = format(date, "%Y"),
+ month = format(date, "%m")) |>
+ group_by(year, month) |>
+ summarise(mean_temp = mean_with_criteria(
+ temperature, max_missing = 3, max_consecutive = 2),
+ .groups = "drop")
+
+monthly_means
+#> # A tibble: 12 × 3
+#> year month mean_temp
+#> <chr> <chr> <dbl>
+#> 1 2020 01 17.1
+#> 2 2020 02 NA
+#> 3 2020 03 13.5
+#> 4 2020 04 15.4
+#> 5 2020 05 16.3
+#> 6 2020 06 14.6
+#> 7 2020 07 NA
+#> 8 2020 08 13.7
+#> 9 2020 09 14.3
+#> 10 2020 10 12.9
+#> 11 2020 11 15.1
+#> 12 2020 12 15.6Months where the missing-data criteria are exceeded will show NA, making it easy to flag them downstream.
calc_annual_anomaly() subtracts the mean of a reference period from every observation. The reference period mean is itself computed with mean_with_criteria(), so the same missing-data safeguards apply.
+set.seed(7)
+
+# Simulate 50 years of annual mean temperatures
+temp_series <- tibble(
+ year = 1971:2020,
+ temperature = 12 + cumsum(rnorm(50, mean = 0.03, sd = 0.4)))
+
+# Define the WMO 1981–2010 climate normal as the reference period
+reference_period <- c(1981, 2010)
+temp_series <- temp_series |>
+ mutate(anomaly = calc_annual_anomaly(temperature,
+ year, period = reference_period))
+
+head(temp_series)
+#> # A tibble: 6 × 3
+#> year temperature anomaly
+#> <int> <dbl> <dbl>
+#> 1 1971 12.9 -3.77
+#> 2 1972 12.5 -4.22
+#> 3 1973 12.2 -4.47
+#> 4 1974 12.1 -4.61
+#> 5 1975 11.8 -4.96
+#> 6 1976 11.4 -5.31
+library(ggplot2)
+
+ggplot(temp_series, aes(x = year, y = anomaly, fill = anomaly > 0)) +
+ geom_col(show.legend = FALSE) +
+ geom_hline(yintercept = 0, linewidth = 0.4) +
+ scale_fill_manual(values = c("#0D94A3", "#AE4E51")) +
+ labs(title = "Annual temperature anomaly",
+ subtitle = paste0("Relative to ", reference_period[1], "\u2013",
+ reference_period[2], " mean"),
+ x = NULL, y = "\u00b0C") +
+ theme_minimal()
If observations are missing inside the reference period, calc_annual_anomaly() passes max_missing and max_consecutive to mean_with_criteria(). If the reference mean cannot be calculated the function returns NA for every year and issues a warning:
+# Introduce missing values in the reference period
+temp_with_gaps <- temp_series$temperature
+temp_with_gaps[11:15] <- NA # years 1981–1985 are missing
+
+anomalies_strict <- calc_annual_anomaly(
+ x = temp_with_gaps,
+ year = temp_series$year,
+ period = reference_period,
+ max_missing = 0, # zero tolerance for missing baseline data
+ max_consecutive = 0)
+#> Warning in calc_annual_anomaly(x = temp_with_gaps, year = temp_series$year, :
+#> Missing values for the anomaly reference period.
+
+head(anomalies_strict)
+#> [1] NA NA NA NA NA NA
+
+# Relax the constraint: allow up to 20 % missing in the reference period
+anomalies_relaxed <- calc_annual_anomaly(
+ x = temp_with_gaps,
+ year = temp_series$year,
+ period = reference_period,
+ max_missing = 0.20,
+ max_consecutive = NULL # no consecutive-missing constraint
+)
+#> Warning in calc_annual_anomaly(x = temp_with_gaps, year = temp_series$year, :
+#> Missing values for the anomaly reference period.
+
+head(anomalies_relaxed)
+#> [1] -4.203734 -4.652443 -4.900160 -5.035077 -5.393346 -5.742258| Argument | +Description | +Accepts | +
|---|---|---|
max_missing |
+Maximum allowable missing values | +Count (integer) or proportion (0–1) | +
max_consecutive |
+Maximum allowable consecutive missing values | +Count (integer) or proportion (0–1) | +
fun |
+Aggregation function (aggregate_with_criteria only) |
+Any function, e.g. mean, sum
+ |
+
period |
+Start and end year of the anomaly baseline | +
+c(start, end) or NULL for full range |
+
Setting a threshold to NULL or 1 disables that constraint entirely.
Developed by Fernando Cagua, David Hodge, Bonnie Farant, Nestor Robinson.
+Site built with pkgdown 2.2.0.
+Developed by Fernando Cagua, David Hodge, Bonnie Farant, Nestor Robinson.
+Site built with pkgdown 2.2.0.
+er.helpers provides two families of colour palettes tailored for environmental reporting at Statistics New Zealand:
| Family | +Prefix | +Use case | +
|---|---|---|
| Statistics NZ web | +pal_snz_* |
+StatsNZ website publications | +
| EA19 report | +pal_ea19_* |
+Environment Aotearoa 2019 print report | +
| Map / point | +pal_point_* |
+Spatial maps and scatter plots | +
Within each family there are palettes for different situations:
+| Suffix | +Purpose | +
|---|---|
| (none) | +Nominal (unordered) categorical variables | +
_alpha2 |
+Comparing a current year to one past year | +
_trend2 |
+Two-level ordinal trend (e.g. improving / worsening) | +
_trend3 |
+Three-level ordinal trend (e.g. improving / indeterminate / worsening) | +
_trend5 |
+Five-level ordinal trend | +
_nztcs_c |
+NZ Threat Classification System — categories | +
_nztcs_s |
+NZ Threat Classification System — sub-categories (SNZ only) | +
An additional signed_sqrt_trans() scale transformation is useful for visualising trend magnitudes that span both negative and positive values.
Use scales::show_col() to display any palette:
+scales::show_col(pal_snz, borders = NA)
+scales::show_col(pal_ea19, borders = NA)
+scales::show_col(pal_point_set1, borders = NA)
Use the base pal_snz / pal_ea19 palettes with scale_fill_manual() or scale_colour_manual() for unordered categorical variables:
+set.seed(1)
+indicator_data <- tibble(
+ indicator = paste0("Indicator ", 1:7),
+ value = runif(7, 50, 150)
+)
+
+ggplot(indicator_data, aes(x = reorder(indicator, value), y = value,
+ fill = indicator)) +
+ geom_col(show.legend = FALSE) +
+ scale_fill_manual(values = pal_snz) +
+ coord_flip() +
+ labs(title = "pal_snz — nominal palette", x = NULL, y = "Value") +
+ theme_minimal()
Trend palettes are designed to pair with order_likelihood_levels() so that colours align with the direction and strength of a trend.
+trend2_df <- tibble(
+ trend = factor(c("Improving", "Worsening")),
+ n = c(12, 8)
+)
+
+ggplot(trend2_df, aes(x = trend, y = n, fill = trend)) +
+ geom_col(show.legend = FALSE) +
+ scale_fill_manual(values = pal_snz_trend2) +
+ labs(title = "pal_snz_trend2", x = NULL, y = "Count") +
+ theme_minimal()
+set.seed(7)
+p_values <- runif(50)
+
+trend5_df <- tibble(
+ p_value = p_values,
+ likelihood = get_likelihood_category(p_value, term_type = "increasing-decreasing") |>
+ order_likelihood_levels()
+) |>
+ count(likelihood)
+
+ggplot(trend5_df, aes(x = likelihood, y = n, fill = likelihood)) +
+ geom_col(show.legend = FALSE) +
+ scale_fill_manual(values = pal_snz_trend5) +
+ labs(title = "pal_snz_trend5 — five-level trend palette",
+ x = NULL, y = "Count") +
+ theme_minimal() +
+ theme(axis.text.x = element_text(angle = 30, hjust = 1))
pal_snz_alpha2 and pal_ea19_alpha2 use a tinted base colour for the earlier year and the full base colour for the current year:
+comparison_df <- tibble(
+ year = factor(c(2019, 2023), levels = c(2019, 2023)),
+ value = c(82, 91)
+)
+
+ggplot(comparison_df, aes(x = year, y = value, fill = year)) +
+ geom_col(show.legend = FALSE, width = 0.5) +
+ scale_fill_manual(values = pal_snz_alpha2) +
+ labs(title = "pal_snz_alpha2 — year comparison palette",
+ x = NULL, y = "Value") +
+ theme_minimal()
pal_snz_nztcs_c (four categories) and pal_snz_nztcs_s (nine sub-categories) are named vectors, so they map automatically to factor levels:
+nztcs_df <- tibble(
+ status = factor(names(pal_snz_nztcs_c),
+ levels = names(pal_snz_nztcs_c)),
+ n = c(45, 120, 18, 310)
+)
+
+ggplot(nztcs_df, aes(x = status, y = n, fill = status)) +
+ geom_col(show.legend = FALSE) +
+ scale_fill_manual(values = pal_snz_nztcs_c) +
+ labs(title = "pal_snz_nztcs_c — NZ Threat Classification",
+ x = NULL, y = "Number of species") +
+ theme_minimal() +
+ theme(axis.text.x = element_text(angle = 15, hjust = 1))
When a continuous variable spans a wide range of both positive and negative values, a standard linear scale compresses small values near zero. The signed_sqrt_trans() transformation stretches both tails symmetrically:
+set.seed(22)
+slopes_df <- tibble(
+ station = paste0("S", 1:20),
+ slope = c(rnorm(10, mean = -2, sd = 0.5),
+ rnorm(10, mean = 8, sd = 3))
+)
+
+ggplot(slopes_df, aes(x = reorder(station, slope), y = slope,
+ fill = slope > 0)) +
+ geom_col(show.legend = FALSE) +
+ scale_y_continuous(trans = signed_sqrt_trans()) +
+ scale_fill_manual(values = c("#0D94A3", "#AE4E51")) +
+ labs(title = "Signed square-root y-axis",
+ x = NULL, y = "Sen's slope (signed\u221a)") +
+ theme_minimal() +
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))
#> # A tibble: 17 × 3
+#> Object Colours Description
+#> <chr> <int> <chr>
+#> 1 pal_snz 9 Nominal — StatsNZ web
+#> 2 pal_snz_alpha2 2 Year comparison — StatsNZ web
+#> 3 pal_snz_trend2 2 Trend 2-level — StatsNZ web
+#> 4 pal_snz_trend3 3 Trend 3-level — StatsNZ web
+#> 5 pal_snz_trend5 5 Trend 5-level — StatsNZ web
+#> 6 pal_snz_nztcs_c 4 NZ TCS categories — StatsNZ web
+#> 7 pal_snz_nztcs_s 9 NZ TCS sub-categories — StatsNZ web
+#> 8 pal_ea19 9 Nominal — EA19 report
+#> 9 pal_ea19_alpha2 2 Year comparison — EA19 report
+#> 10 pal_ea19_trend2 2 Trend 2-level — EA19 report
+#> 11 pal_ea19_trend3 3 Trend 3-level — EA19 report
+#> 12 pal_ea19_trend5 5 Trend 5-level — EA19 report
+#> 13 pal_ea19_nztcs_c 4 NZ TCS categories — EA19 report
+#> 14 pal_point_set1 9 Nominal — maps/points
+#> 15 pal_point_trend2 2 Trend 2-level — maps/points
+#> 16 pal_point_trend3 3 Trend 3-level — maps/points
+#> 17 pal_point_trend5 5 Trend 5-level — maps/points
+Developed by Fernando Cagua, David Hodge, Bonnie Farant, Nestor Robinson.
+Site built with pkgdown 2.2.0.
+