### Install and Run Example Application Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Installs the shinyscholar package with all its dependencies and then runs the example Shiny application provided with the package. This demonstrates the package's features and structure. ```r install.packages("shinyscholar", dependencies = TRUE) library(shinyscholar) run_shinyscholar() ``` -------------------------------- ### Launch Example App with run_shinyscholar Source: https://context7.com/simon-smart88/shinyscholar/llms.txt The `run_shinyscholar` function launches the example shinyscholar application, demonstrating all framework features. It can be run with dependencies installed, with a pre-loaded session file, or on a specific network port. ```r # Install with dependencies for the example app install.packages("shinyscholar", dependencies = TRUE) # Run the example application library(shinyscholar) run_shinyscholar() # Run with a pre-loaded session file run_shinyscholar(load_file = "~/saved_session.rds") # Run on a specific port run_shinyscholar(port = 8080) ``` -------------------------------- ### Install Local Package with devtools::install_local() Source: https://github.com/simon-smart88/shinyscholar/blob/master/inst/shiny/modules/template_create.md After extracting the generated .zip file, navigate to the folder and run this command to install the application package locally. This makes the application runnable. ```r devtools::install_local() ``` -------------------------------- ### Install Local Package Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Installs a local R package, typically used for development. The `force=TRUE` argument overwrites any existing installation. Ensure the `path` points to the correct directory of your package. ```r devtools::install_local(path = "~/Documents/demo", force=TRUE) ``` -------------------------------- ### Install shinyscholar from GitHub Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Installs the shinyscholar package directly from its GitHub repository using the 'remotes' package. This method allows for installing development versions or specific branches. ```r install.packages("remotes") remotes::install_github("simon-smart88/shinyscholar") ``` -------------------------------- ### Run Generated Application with ::run_() Source: https://github.com/simon-smart88/shinyscholar/blob/master/inst/shiny/modules/template_create.md Once the application package has been installed locally, you can run the application by calling this function. Replace `` with the actual name you provided for your application. ```r ::run_() ``` -------------------------------- ### End-to-end Testing with Shinytest2 Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Demonstrates how to initiate and manage asynchronous tasks within end-to-end tests using shinytest2. It covers starting tasks, setting timeouts, signaling completion via Shiny.setInputValue, and waiting for these signals in tests. ```r app$click(selector = "#-run") # Set timeout parameter in shinytest2::AppDriver() to allow sufficient time for the function to run. shinyjs::runjs("Shiny.setInputValue('-complete', 'complete');") app$wait_for_value(input = "-complete") ``` -------------------------------- ### Install shinyscholar from CRAN Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Installs the shinyscholar package from the Comprehensive R Archive Network (CRAN). This is the standard method for installing R packages. ```r install.packages("shinyscholar") ``` -------------------------------- ### Set MiKTeX Path for PDF Generation in R Source: https://github.com/simon-smart88/shinyscholar/blob/master/inst/shiny/modules/rep_markdown.md This R code snippet demonstrates how to set the system's PATH environment variable to include the MiKTeX bin directory, which is necessary for generating PDF documents from R Markdown files on Windows. It assumes MiKTeX is installed in the default location. ```r d <- "C:/Program Files/MiKTeX 2.9/miktex/bin/x64/" Sys.setenv(PATH=paste(Sys.getenv("PATH"), d, sep=";")) ``` -------------------------------- ### Create Shiny Application Skeleton with create_template Source: https://context7.com/simon-smart88/shinyscholar/llms.txt The `create_template` function generates a complete skeleton Shiny application. It allows customization of modules, components, shared objects, author information, and inclusion of features like mapping, tables, code download, and asynchronous operations. The generated application can then be installed and run. ```r # Define modules for your application modules <- data.frame( "component" = c("load", "load", "plot", "plot"), "long_component" = c("Load data", "Load data", "Plot data", "Plot data"), "module" = c("user", "database", "histogram", "scatter"), "long_module" = c("Upload your own data", "Query a database to obtain data", "Plot the data as a histogram", "Plot the data as a scatterplot"), "map" = c(TRUE, TRUE, FALSE, FALSE), "result" = c(FALSE, FALSE, TRUE, TRUE), "rmd" = c(TRUE, TRUE, TRUE, TRUE), "save" = c(TRUE, TRUE, TRUE, TRUE), "download" = c(FALSE, FALSE, TRUE, TRUE), "async" = c(FALSE, TRUE, FALSE, FALSE) ) # Specify objects shared between modules common_objects <- c("raster", "histogram", "scatter") # Create the template create_template( path = "~/Documents", name = "demo", common_objects = common_objects, modules = modules, author = "Your Name", include_map = TRUE, include_table = TRUE, include_code = TRUE, install = TRUE ) # Install and run the generated app devtools::install_local("~/Documents/demo", force = TRUE) demo::run_demo() ``` -------------------------------- ### Asynchronous Operations with ExtendedTask in Shiny Source: https://context7.com/simon-smart88/shinyscholar/llms.txt This snippet demonstrates how to implement asynchronous operations using ExtendedTask in Shiny, starting from version 1.8.1. It covers setting up the task, invoking it with user input, and handling the results, including error management. This approach prevents UI freezing during long computations by offloading them to a background process. The module function must also support an 'async' parameter to handle potential errors gracefully. ```r # In module server (inst/shiny/modules/data_fetch.R) # Create ExtendedTask above observeEvent common$tasks$data_fetch <- ExtendedTask$new(function(...) { mirai::mirai(run(...), environment(), .args = list(run = data_fetch)) }) |> bslib::bind_task_button("run") # Invoke task when button clicked observeEvent(input$run, { results$resume() # Resume result observer # Store metadata now (before async execution) common$meta$data_fetch$used <- TRUE common$meta$data_fetch$param <- input$param # Launch async task common$tasks$data_fetch$invoke( param = input$param, logger = common$logger, async = TRUE ) }) # Separate observer to handle results results <- observe({ result <- common$tasks$data_fetch$result() results$suspend() # Prevent loop # Check if result is error or data if (inherits(result, "character")) { common$logger |> writeLog(type = "error", result) } else { common$data <- result do.call("data_fetch_module_map", list(map, common)) shinyjs::runjs("Shiny.setInputValue('data_fetch-complete', 'complete');") } }) # Module function must support async parameter data_fetch_f <- function(param, logger = NULL, async = FALSE) { result <- tryCatch({ process(param) }, error = function(e) { return(async |> asyncLog(e$message, type = "error")) }) return(result) } ``` -------------------------------- ### Snapshot Dependencies using renv::snapshot() Source: https://github.com/simon-smart88/shinyscholar/blob/master/inst/shiny/modules/rep_renv.md This function captures the exact versions of all packages used in the analysis, creating a lock file for future restoration. It is a core component for ensuring computational research reproducibility. ```r renv::snapshot() ``` -------------------------------- ### Create ShinyScholar App Template (R) Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Initializes a new ShinyScholar app template with specified components, modules, and common objects. The function allows customization of included features and module functionalities. Dependencies include the shinyscholar package. ```R modules <- data.frame( "component" = c("load", "load", "plot", "plot"), "long_component" = c("Load data", "Load data", "Plot data", "Plot data"), "module" = c("user", "database", "histogram", "scatter"), "long_module" = c("Upload your own data", "Query a database to obtain data", "Plot the data as a histogram", "Plot the data as a scatterplot"), "map" = c(TRUE, TRUE, FALSE, FALSE), "result" = c(FALSE, FALSE, TRUE, TRUE), "rmd" = c(TRUE, TRUE, TRUE, TRUE), "save" = c(TRUE, TRUE, TRUE, TRUE), "download" = c(FALSE, FALSE, TRUE, TRUE), "async" = c(FALSE, TRUE, FALSE, FALSE)) common_objects = c("raster", "histogram", "scatter") shinyscholar::create_template(path = file.path("~", "Documents"), name = "demo", author = "Simon E. H. Smart", include_map = TRUE, include_table = TRUE, include_code = TRUE, common_objects = common_objects, modules = modules, install = TRUE) ``` -------------------------------- ### Restore Dependencies using renv::restore() Source: https://github.com/simon-smart88/shinyscholar/blob/master/inst/shiny/modules/rep_renv.md This function reinstalls the package versions specified in a lock file, allowing for the restoration of a previous analysis environment. It is used in conjunction with the output of renv::snapshot(). ```r renv::restore() ``` -------------------------------- ### Run Shiny Application Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Runs a Shiny application from a specified package. This command is useful for testing or demonstrating the application during development. It assumes the application is located within the package's structure. ```r shiny::runApp(system.file('shiny', package='demo')) ``` ```r demo::run_demo() ``` -------------------------------- ### Setting PATH Environment Variable for MiKTeX Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Provides R code to dynamically set the PATH environment variable on Windows to include the MiKTeX bin directory, which is necessary for PDF generation of session code when RStudio cannot locate pdflatex.exe. ```r Sys.setenv(PATH=paste(Sys.getenv("PATH"),"C:/Program Files/MiKTeX 2.9/miktex/bin/x64/",sep=";")) ``` -------------------------------- ### Add New Module to Existing App with create_module Source: https://context7.com/simon-smart88/shinyscholar/llms.txt The `create_module` function is used to add a new module to an existing shinyscholar application. It generates necessary files for the module, including UI, server, R Markdown template, guidance, configuration, computational function, and tests. Manual updates to global configuration and R Markdown files are required after creation. ```r # Navigate to your app directory setwd("~/Documents/demo") # Create a new module with map, result, and rmd support create_module( id = "analysis_regression", dir = "~/Documents/demo", map = TRUE, result = TRUE, rmd = TRUE, save = TRUE, download = TRUE, async = FALSE ) # This creates: # - inst/shiny/modules/analysis_regression.R (UI and server) # - inst/shiny/modules/analysis_regression.Rmd (reproducible template) # - inst/shiny/modules/analysis_regression.md (guidance) # - inst/shiny/modules/analysis_regression.yml (configuration) # - R/analysis_regression_f.R (computational function) # - tests/testthat/test-analysis_regression.R (tests) # After creating, manually update: # - inst/shiny/global.R: Add to base_module_configs # - inst/shiny/Rmd/text_intro_tab.Rmd: Add to intro tab # - inst/shiny/common.R: Add any new data objects ``` -------------------------------- ### Module Configuration File Structure Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md A YAML configuration file for loading modules. The `package` field lists R packages required by the module for citation purposes. The `short_name` field provides a user-friendly label for module selection in the UI. ```yaml module: my_module_name short_name: "My Analysis Module" package: - dplyr - shiny version: 1.0.0 ``` -------------------------------- ### Display and Dismiss Loading Modals - R Source: https://context7.com/simon-smart88/shinyscholar/llms.txt Provides functions to display a temporary loading modal during computationally intensive operations and dismiss it once complete or an error occurs. This improves user experience by providing feedback on ongoing processes. ```r # Show modal before long operation observeEvent(input$process, { show_loading_modal("Processing large dataset. This may take several minutes...") result <- tryCatch({ expensive_computation(data) }, error = function(e) { close_loading_modal() common$logger |> writeLog(type = "error", e$message) NULL }) close_loading_modal() if (!is.null(result)) { common$result <- result common$logger |> writeLog(type = "complete", "Processing complete") } }) ``` -------------------------------- ### Asynchronous Task Logging with ExtendedTask Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Illustrates how to handle logging within asynchronous module functions. Since `common$logger` is not directly accessible in a separate R session, errors are passed using `asyncLog` to be returned when the task is asynchronous or passed to `stop()` otherwise. The `async` parameter must be added to the module function. ```r return(async |> asyncLog("message", type = "error")) ``` -------------------------------- ### Shiny Module Server Function Logic Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Outlines the server-side logic for a Shiny module. It includes an observeEvent triggered by an actionButton, with distinct blocks for input validation (warning), function calls, storing results in 'common', metadata handling, and triggering subsequent actions. The result block renders outputs, and the return block handles saving and loading of input states. ```r module_server <- function(id, common) { moduleServer(id, function(input, output, session) { observeEvent(input$run_module, { # Warning block: Validate inputs common$logger |> writeLog("Checking inputs...") req(input$input_id, input$numeric_input) # Function call block: Pass common objects and inputs result <- some_module_function(common, input$input_id, input$numeric_input) # Load into common block: Store results common$results[[id]] <- result # Metadata block: Store metadata common$meta[[id]] <- metadata(input) # Trigger block: Trigger actions elsewhere trigger(id, "run_module") }) # Result block: Render outputs output$module_output <- renderPlot({ # Plotting logic using common$results[[id]] or other common objects plot(common$results[[id]]) }) # Return block: Save and load input states save_and_load({ list(select_date = input$input_id, numeric_val = input$numeric_input) }) }) } ``` -------------------------------- ### Mapping Results from Asynchronous Tasks Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Explains how to integrate results from asynchronous tasks into the mapping functionality. Unlike the default implementation, the `map` object is passed as an argument to the module server function. The mapping is then performed by calling `do.call` with the specific module's mapping function once the result is available. ```r do.call("_module_map", list(map, common)) ``` -------------------------------- ### Generate Input Save/Load Functionality - R Source: https://context7.com/simon-smart88/shinyscholar/llms.txt Automatically generates functions to save and load Shiny module input states, preserving application state across sessions. It supports standard Shiny inputs and some from shinyWidgets, with provisions for custom inputs. ```r # Run on all modules in your app save_and_load("~/Documents/demo") # Or target a specific module save_and_load("~/Documents/demo", module = "plot_histogram") # This scans the module UI for input widgets and generates: # 1. save = function() {list( # date = input$date, # bins = input$bins, # color = input$color # )} # 2. load = function(state) { # updateDateInput(session, "date", value = state$date) # updateNumericInput(session, "bins", value = state$bins) # updateSelectInput(session, "color", selected = state$color) # } # Supported input types: # - All standard shiny inputs (textInput, numericInput, etc.) # - shinyWidgets::materialSwitch # - Special handling for dateRangeInput, fileInput # For custom inputs, add manual code between markers: # save = function() {list( # ### Manual save start # custom_value = get_custom_value() # ### Manual save end # date = input$date # )} ``` -------------------------------- ### Generate Module Metadata - R Source: https://context7.com/simon-smart88/shinyscholar/llms.txt Automatically adds reproducibility tracking code to Shiny modules. It extracts input widgets and generates metadata storage, aiding in reproducible research. Manual follow-up might be required for dynamically created inputs or inputs from external packages. ```r # Create a test app create_template( path = tempdir(), name = "testapp", common_objects = c("data"), modules = data.frame( component = "load", long_component = "Load data", module = "csv", long_module = "Load CSV file", map = FALSE, result = TRUE, rmd = TRUE, save = TRUE, download = FALSE, async = FALSE ), author = "Test", install = FALSE ) # Add input widgets to your module's UI and function call in server # Then auto-generate metadata tracking metadata("~/testapp") # Or target a specific module metadata("~/testapp", module = "load_csv") # This automatically adds to the module: # 1. common$meta$load_csv$used <- TRUE # 2. common$meta$load_csv$inputname <- input$inputname (for each input) # 3. Rmd function: load_csv_knit = !is.null(common$meta$load_csv$used) # 4. Rmd function: load_csv_inputname = common$meta$load_csv$inputname # 5. Rmd file: {{load_csv_inputname}} placeholders # Manual follow-up required: # - Check dynamically created inputs are included # - Add inputs from other packages (DT, leaflet) # - Update .Rmd to use the generated variables ``` -------------------------------- ### Handling Asynchronous Task Results Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Demonstrates the pattern for observing and processing results from an asynchronous task. A separate `observe()` block named `results` listens for task completion. To prevent infinite loops, the observer is suspended after results are calculated (`results$suspend()`) and reactivated before the next task invocation (`results$resume()`). ```r observe({ # ... observer logic ... results$suspend() }) # ... task invocation ... results$resume() ``` -------------------------------- ### Log Messages with writeLog Source: https://context7.com/simon-smart88/shinyscholar/llms.txt The `writeLog` function provides a flexible logging system that works both inside and outside Shiny applications for user notifications. When used within a Shiny module, messages appear in a log window with icons indicating severity. Outside of Shiny, messages are directed to the console. The logger can be NULL, in which case messages use standard R functions like `stop()`, `warning()`, or `message()`. ```r # Inside a Shiny module - messages appear in log window with icons observeEvent(input$process, { common$logger |> writeLog("Starting data processing") common$logger |> writeLog(type = "info", "This is an informational message") common$logger |> writeLog(type = "warning", "Warning: data contains missing values") common$logger |> writeLog(type = "error", "Invalid input: value must be positive") common$logger |> writeLog(type = "complete", "Processing finished successfully") }) # Outside Shiny (in standalone function) - messages go to console my_function <- function(data, logger = NULL) { logger |> writeLog("Processing data...") if (any(is.na(data))) { logger |> writeLog(type = "warning", "Data contains NA values") } result <- process_data(data) logger |> writeLog(type = "complete", "Done") return(result) } # When logger is NULL, messages use stop(), warning(), or message() my_function(data, logger = NULL) # Prints to console ``` -------------------------------- ### Query NASA Earthdata API - R Source: https://context7.com/simon-smart88/shinyscholar/llms.txt Fetches raster data (e.g., FAPAR) from the NASA Earthdata API within a specified polygon and date range. The function includes comprehensive error handling, input validation, and logging, suitable for use in Shiny applications. ```r # Get authentication token token <- get_nasa_token( username = "your_earthdata_username", password = "your_earthdata_password" ) # Define area of interest as polygon matrix poly <- matrix(c(0.5, 0.5, 1, 1, 0.5, # longitudes 52, 52.5, 52.5, 52, 52), # latitudes ncol = 2) colnames(poly) <- c("longitude", "latitude") # Load FAPAR raster data for specific date raster <- select_query( poly = poly, date = "2023-06-20", token = token, logger = NULL # Use logger in Shiny app ) # Inside a Shiny module with full error handling observeEvent(input$run, { if (is.null(common$poly)) { common$logger |> writeLog(type = "error", "Please draw a rectangle on the map") return() } show_loading_modal("Loading satellite imagery...") raster <- select_query( poly = common$poly, date = as.character(input$date), token = token(), logger = common$logger ) close_loading_modal() if (!is.null(raster)) { common$raster <- raster common$meta$select_query$used <- TRUE common$meta$select_query$date <- as.character(input$date) trigger("select_query") show_map(parent_session) } }) # The function validates inputs, checks API availability, # downloads and stitches tiles, handles missing data, # and provides detailed logging of issues ``` -------------------------------- ### Accessing 'common' object in Shiny tests Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Demonstrates how to access the 'common' object within end-to-end tests using shinytest2. This is crucial for verifying the state of shared data structures after module execution. It also shows an alternative method for accessing 'common' via saving and loading the session state. ```R common <- app$get_value(export = "common") ``` ```R app$set_inputs(main = "Save") save_file <- app$get_download("core_save-save_session", filename = save_path) common <- readRDS(save_file) ``` -------------------------------- ### Bind Task Button for Asynchronous Operations Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md This code snippet demonstrates how to bind an asynchronous task to a button using `bslib::bind_task_button`. It initializes an `ExtendedTask` that wraps a `mirai::mirai` call for a module's function and associates it with a button named 'run'. The button is disabled while the task is active. ```r common$tasks$ <- ExtendedTask$new(function(...) { mirai::mirai(run(...), environment(), .args = list(run = )) }) |> bslib::bind_task_button("run") ``` -------------------------------- ### Shiny Module UI Function Structure Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Defines the structure for a Shiny module's UI function. It should contain only input widgets, with input IDs wrapped in `ns()` for uniqueness. An actionButton is used to trigger server-side computations, though reactive updates can be achieved by removing it. ```r module_ui <- function(id, common) { ns <- NS(id) tagList( # Input widgets with ns() for unique IDs selectInput(ns("input_id"), "Select Option", choices = c("A", "B")), numericInput(ns("numeric_input"), "Enter Value", value = 10), actionButton(ns("run_module"), "Run Module") ) } ``` -------------------------------- ### Invoking Asynchronous Module Task Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Shows how to trigger an asynchronous task within an `observeEvent` function. The `common$tasks$$invoke()` method is called with the necessary arguments for the module's function. Metadata should be stored at this point when the function is called. ```r common$tasks$$invoke() ``` -------------------------------- ### Shiny Module Map Integration Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Handles map-related outputs for a module when map integration is enabled. It utilizes a `leafletProxy` object provided by the main server function, allowing for direct piping of Leaflet functions (e.g., `addRasterImage()`) to the map. ```r module_map <- function(id, common) { ns <- NS(id) tagList( # Map output placeholder, actual Leaflet functions are piped to map object # Example: map |> addRasterImage(common$results[[id]]$raster_layer) ) } ``` -------------------------------- ### Shiny Module R Markdown Generation Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Creates a list of objects passed to the module's R Markdown template for reproduction. Includes a boolean (`_knit`) to control markdown inclusion and allows for dynamic substitution of module settings within the .Rmd file using `{{variable_name}}` syntax. ```r module_rmd <- function(id, common) { list( "_knit" = TRUE, # Controls if markdown is included "setting_value" = "some_value", # Example setting for Rmd "module_setting" = "{{module_setting}}" # Placeholder for Rmd substitution ) } ``` -------------------------------- ### Accessing logger object in Shiny tests Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Illustrates how to access and check messages within the logger object during end-to-end tests using shinytest2. This is important for verifying that logging mechanisms are functioning correctly within the application. ```R logger <- app$get_value(export = "logger") expect_true(grepl("**"), logger)) ``` -------------------------------- ### Reset Application Data - R Source: https://context7.com/simon-smart88/shinyscholar/llms.txt Resets all data within the Shiny application's common structure, excluding logger and tasks, and triggers UI updates to clear map layers and hide module results. This is useful for providing a clean slate for the user. ```r # In a module that needs to clear all data observeEvent(input$clear_all, { # Clears all common objects except logger and tasks # Triggers map clearing and hides all module results reset_data(common) # Logger shows all cleared modules common$logger |> writeLog("Application reset") }) # What it does: # 1. Calls common$reset() - sets all objects to NULL except logger/tasks # 2. trigger("clear_map") - removes all map layers # 3. For each module: trigger(module) and hide download buttons ``` -------------------------------- ### Shiny Module Result Rendering Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md Defines the function responsible for rendering the module's output. This typically involves using `*Output()` functions (e.g., `plotOutput()`, `tableOutput()`) with object IDs wrapped in `ns()` to ensure uniqueness within the module. ```r module_result <- function(id, common) { ns <- NS(id) tagList( plotOutput(ns("module_output")) ) } ``` -------------------------------- ### R Markdown Template Structure Source: https://github.com/simon-smart88/shinyscholar/blob/master/README.md A template for R Markdown files used to reproduce module analyses. Objects passed from the `*_module_rmd` function are available within the knitted document. Settings can be embedded using double curly braces `{{variable_name}}`, requiring quotes for character strings. ```rmarkdown --- title: "Module Analysis Report" output: html_document params: setting_value: !r "default_value" --- # Analysis Results This report details the analysis performed by the module. Module setting used: `{{module_setting}}` ``` -------------------------------- ### Plot Raster Histogram Semi-Automatically using R Source: https://github.com/simon-smart88/shinyscholar/blob/master/inst/shiny/modules/plot_semi.md This R function, `plot_hist()`, processes raster image values for histogram plotting. It leverages the `terra` package to extract raster values and the base R `hist()` function for visualization. The number of bins can be specified by the user, and the module automatically reruns when inputs change. ```r plot_hist <- function(raster_data, bins = 30) { # Extract values from the raster object values <- terra::values(raster_data) # Plot the histogram hist(values, breaks = bins, main = "Histogram of Raster Values", xlab = "Values", ylab = "Frequency") return(invisible(values)) # Optionally return the extracted values } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.