R/viz_nue.R

Defines functions plot_nue_compare

Documented in plot_nue_compare

#' Plot NUE Comparison
#'
#' Creates a bar chart comparing NUE metrics across different groups (e.g., Treatments or Sites).
#' Includes error bars (Standard Error).
#'
#' @param data A dataframe containing the results.
#' @param x_var The column name to group by (e.g., "Treatment", "Year").
#' @param y_var The NUE metric to plot (e.g., "AE", "NRE").
#' @return A ggplot object.
#' @export
#' @import ggplot2
#' @importFrom magrittr %>%
#' @importFrom stats sd
#' @importFrom dplyr group_by summarise n
#' @importFrom rlang .data
#' @examples
#' # Create dummy data
#' df <- data.frame(
#'   Treat = c("A", "A", "B", "B"),
#'   AE = c(10, 12, 20, 22)
#' )
#'
#' # Plot
#' plot_nue_compare(df, x_var = "Treat", y_var = "AE")
plot_nue_compare <- function(data, x_var, y_var) {
  
  # Ensure column names are symbols for ggplot
  x_sym <- dplyr::sym(x_var)
  y_sym <- dplyr::sym(y_var)
  
  # Summarize data (Mean + SE)
  # We use the pipe (%>%) here, which is why we imported it from magrittr above
  summary_df <- data %>%
    dplyr::group_by(!!x_sym) %>%
    dplyr::summarise(
      Mean = mean(!!y_sym, na.rm = TRUE),
      SE = sd(!!y_sym, na.rm = TRUE) / sqrt(dplyr::n())
    )
  
  # Plot
  # We use .data$Mean to tell R explicitly these are columns (fixes the Note)
  p <- ggplot(summary_df, aes(x = !!x_sym, y = .data$Mean, fill = !!x_sym)) +
    geom_bar(stat = "identity", width = 0.7, color = "black") +
    geom_errorbar(aes(ymin = .data$Mean - .data$SE, ymax = .data$Mean + .data$SE), width = 0.2) +
    labs(
      title = paste("Comparison of", y_var),
      y = y_var,
      x = x_var
    ) +
    theme_minimal() +
    theme(legend.position = "none")
  
  return(p)
}

# This tells R's check system to ignore these variable names during the check
utils::globalVariables(c("Mean", "SE"))

Try the NUETON package in your browser

Any scripts or data that you put into this service are public.

NUETON documentation built on Dec. 18, 2025, 1:07 a.m.