Package 'windcut'

Title: Weather Time Series Feature Engineering for Plant Disease Epidemiology
Description: Tools for transforming weather time series into model-ready features for plant disease epidemiology. The package supports relative-time window panes around biological reference dates, biologically interpretable weather summaries, feature screening, and functional data analysis workflows for comparing weather trajectories between disease classes.
Authors: Kaique S. Alves [aut, cre] (ORCID: <https://orcid.org/0000-0001-9187-0252>)
Maintainer: Kaique S. Alves <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0
Built: 2026-12-05 20:05:06 UTC
Source: https://github.com/cran/windcut

Help Index


Aggregate Weather Observations to Daily Data

Description

Converts sub-daily weather observations to one row per day, optionally within each site or location. The same statistics style used by the window workflow is supported here: use a character vector to apply the same statistics to every variable, or use a named list to choose different statistics for different variables. The special .conditions entry can be used for multivariable summaries within each daily group.

Usage

aggregate_weather_daily(
  weather,
  id_col = NULL,
  time_col = "time",
  date_col = "date",
  weather_cols,
  statistics,
  keep_time = TRUE,
  name_prefix = "daily"
)

Arguments

weather

A weather data frame.

id_col

Optional site, location, or series identifier column. If supplied, aggregation is done separately within each ID.

time_col

Name of the timestamp column. Use NULL when the input data already have a day/date column and no separate timestamp column is needed.

date_col

Name of the day/date column. If this column already exists in weather, it is used for daily grouping. If it does not exist, aggregate_weather_daily() derives it from time_col and creates it in the output.

weather_cols

Required character vector of existing numeric weather columns. Column names must be unique, non-missing, and non-empty. If named, every entry must have a unique, non-missing, non-empty output alias; .conditions is reserved. No columns are inferred. Use character() explicitly for condition-only summaries.

statistics

Required summary specification. Use a non-empty character vector to apply the same statistics to all weather_cols, such as c("mean", "sd", "IQR"). Alternatively, use a named list keyed by every selected column's output alias (or column name when unnamed), with no unknown keys. Each entry must be a non-empty character vector or a nested named list of functions or single function names, for example list(temp = list(avg = "mean", spread = stats::sd)). Statistic names must be unique, non-missing, and non-empty. No summaries are inferred. The optional .conditions entry is a named list of multivariable condition summaries such as count_when(temp >= 18 & rh >= 90).

keep_time

If TRUE, include a daily POSIXct time column at midnight. This requires either time_col or an existing date_col.

name_prefix

Prefix used in aggregated weather columns. The default creates names such as daily_mean_temp and daily_sum_rain.

Details

The configured ID, time, and date columns cannot be selected in weather_cols. Summary output names must be unique and must not overwrite retained metadata. An input with no rows is rejected.

Value

A daily data frame sorted by ID and date.

Examples

hourly <- simulate_weather_series(days = 5, n_series = 2, id_col = "site_id", seed = 1)

aggregate_weather_daily(
  hourly,
  id_col = "site_id",
  weather_cols = c("temp", "rh", "rain"),
  statistics = list(temp = c("mean", "max"), rh = "mean", rain = "sum")
)

Conditional value summary functions

Description

These functions summarize only values that satisfy a threshold condition. ⁠sum_*()⁠ returns zero when valid observations exist but none satisfy the condition. ⁠mean_*()⁠ returns NA_real_ when no value satisfies the condition.

Usage

sum_above(threshold, na.rm = TRUE)

sum_at_or_above(threshold, na.rm = TRUE)

sum_below(threshold, na.rm = TRUE)

sum_between(lower, upper, inclusive = TRUE, na.rm = TRUE)

mean_above(threshold, na.rm = TRUE)

mean_at_or_above(threshold, na.rm = TRUE)

mean_below(threshold, na.rm = TRUE)

mean_between(lower, upper, inclusive = TRUE, na.rm = TRUE)

Arguments

threshold

A single finite numeric threshold.

na.rm

If TRUE, missing values are ignored. For proportion functions, the denominator is the number of non-missing observations.

lower, upper

Single finite numeric limits. lower must be less than or equal to upper.

inclusive

If TRUE, values equal to the boundary are included.

Value

A function that takes a numeric vector and returns one numeric value.

Examples

sum_above(0)(c(0, 1.2, 3.4, NA))
mean_between(18, 26)(c(14, 20, 22, 30))

Example Weather Data

Description

Generates a small synthetic hourly weather time series that can be used in examples, tests, and package demonstrations.

Usage

example_weather_data(
  start = as.POSIXct("2024-01-01 00:00:00", tz = "UTC"),
  days = 30
)

Arguments

start

Start time for the series.

days

Number of days to generate.

Value

A data frame with hourly weather observations.


Extract Features from Retained FDA Intervals

Description

Converts retained FDA intervals into ordinary subject-level predictors for downstream modeling.

Usage

extract_fda_features(
  analysis,
  alpha = NULL,
  value_cols = NULL,
  prefix = "fda",
  statistics = "mean"
)

Arguments

analysis

A windcut_fda_analysis object returned by run_fda_analysis().

alpha

Significance level used to select retained intervals. If NULL, the first alpha value stored in analysis is used.

value_cols

Optional subset of weather variables to extract.

prefix

Prefix used in feature names.

statistics

Interval statistics to compute. Use function names such as "mean", "sd", and "IQR", a named list of custom functions, or a named list by variable. When using a variable-level list, .default can supply statistics for variables not named explicitly.

Value

A wide data frame with one row per subject and one column per extracted FDA feature.


Extract Features from Functional Intervals

Description

Uses one or more time intervals to compute subject-level summaries from a long-format weather series. This is useful after interval-wise testing has identified periods of functional divergence.

Usage

extract_interval_features(
  data,
  id_col,
  time_col,
  value_col,
  intervals,
  prefix = NULL,
  statistics = "mean"
)

Arguments

data

A data frame in long format.

id_col

Subject identifier column.

time_col

Time column, such as relative day or days after planting.

value_col

Measured series column.

intervals

A data frame with start and end columns.

prefix

Prefix used when naming the resulting features.

statistics

Interval statistics to compute. Use function names such as "mean", "sd", and "IQR", or a named list of custom functions.

Value

A wide data frame with one row per subject and one column per interval-derived feature.


Demo Data for Functional Data Analysis Workflows

Description

A bundled dataset for the functional data analysis tutorial.

Format

A list with three components:

weather_daily

Daily weather curves for multiple simulated sites, using the daily_<statistic>_<variable> naming style used in the window-pane tutorials.

assessments

One binary disease assessment per site with wm and wm_class.

variable_specs

A data frame of FDA variable names and display labels.

Details

The data were created from the package's simulation functions and then bundled so the FDA vignette can focus on interpretation, smoothing, interval testing, and feature extraction.


Fit a Function-on-Scalar Model from an FDA Workflow

Description

Fits a binary-group function-on-scalar model for one variable stored in a run_fda_analysis() result. The group contrast is created automatically from the reference and comparison groups used in the FDA workflow.

Usage

fit_fda_group_model(
  analysis,
  value_col,
  reference_score = -1,
  comparison_score = 1,
  formula = y ~ x,
  ...
)

Arguments

analysis

A windcut_fda_analysis object returned by run_fda_analysis().

value_col

Weather variable to model.

reference_score

Numeric score assigned to the reference group.

comparison_score

Numeric score assigned to the comparison group.

formula

Formula passed to functional_on_scalar(). Defaults to y ~ x.

...

Additional arguments passed to functional_on_scalar().

Value

The fitted pffr model object.


Summarise Functional Curves by Group

Description

Computes mean functional curves by group and, when exactly two groups are present, also returns the pointwise difference between those curves.

Usage

functional_group_summary(
  data,
  id_col,
  time_col,
  value_col,
  group_col,
  time_grid = NULL,
  method = c("none", "lowess", "spline"),
  smooth_args = list()
)

Arguments

data

A data frame in long format.

id_col

Subject identifier column.

time_col

Time column, such as relative day or days after planting.

value_col

Measured series column.

group_col

Grouping column, such as disease status.

time_grid

Optional grid where the summary curves are evaluated. If NULL, the sorted observed time values are used. Supplying a denser grid is useful when plotting smoothed curves as continuous functions.

method

Smoothing method used on the group mean curves. One of "none", "lowess", or "spline".

smooth_args

Named list of extra arguments passed to the smoothing method. For "lowess", a common choice is list(f = 0.2). For "spline", typical choices include list(df = 12) or list(spar = 0.6).

Value

A list with grouped summary tables and, when two groups are present, pointwise difference tables. The returned object includes summary, difference, raw_summary, raw_difference, method, and smooth_args.


Run an Interval-Wise Functional Test

Description

Runs fdatest::ITP2bspline() to compare two groups of functional observations evaluated on the same grid.

Usage

functional_interval_test(
  group0,
  group1,
  n_permutations = 1000,
  alpha = 0.05,
  time = NULL,
  quiet = TRUE,
  min_interval_length = 1
)

Arguments

group0

Numeric matrix for the reference group.

group1

Numeric matrix for the comparison group.

n_permutations

Number of permutations used by the interval-wise test.

alpha

Significance level used when extracting intervals.

min_interval_length

Minimum number of consecutive tested time points required for an interval to be retained. For daily series, this is the minimum number of consecutive days. Defaults to 1. This post-test filter does not alter the corrected p-values.

time

Numeric vector of time values corresponding to matrix columns.

quiet

Logical; if TRUE, suppresses routine console output emitted by fdatest::ITP2bspline().

Value

A list with the raw test object, corrected p-values and indicators for threshold crossing and interval retention, the threshold-crossing and retained time values, and a table of retained intervals.


Fit a Function-on-Scalar Regression

Description

Fits a function-on-scalar regression with refund::pffr() for cases where a scalar response or contrast explains a functional weather series measured on a common grid.

Usage

functional_on_scalar(y, x, yind, formula = y ~ x, ...)

Arguments

y

A numeric matrix with subjects in rows and time values in columns.

x

A numeric vector or data frame of scalar predictors.

yind

Numeric vector of time values matching the matrix columns.

formula

Formula for the scalar part of the model. Defaults to y ~ x.

...

Additional arguments passed to refund::pffr().

Value

The fitted pffr model object.


Create a Functional Matrix from Long Data

Description

Converts long-format repeated measurements into a common-grid matrix suitable for functional analyses. Each row corresponds to one subject and each column to one time value, such as days after planting.

Usage

make_functional_matrix(
  data,
  id_col,
  time_col,
  value_col,
  time_grid = NULL,
  fill = NA_real_
)

Arguments

data

A data frame in long format.

id_col

Subject identifier column.

time_col

Time column, such as relative day or days after planting.

value_col

Measured series column.

time_grid

Optional vector defining the common time grid. If NULL, the sorted unique values in time_col are used.

fill

Value used for missing combinations.

Value

A list with y, time, and id.


Create Candidate Relative-Time Windows

Description

Generates windows relative to a reference date. Negative offsets are before the reference date, zero is the reference date, and positive offsets are after the reference date. Use fixed-width windows for the classic window-pane scan, where one exposure duration slides through the relative-time range. Use variable-width windows when you also want to scan alternative exposure durations.

Usage

make_windows(
  min_offset = -30,
  max_offset = -1,
  width = 5,
  slide_by = 1,
  type = c("fixed", "variable"),
  reference_col = NULL
)

Arguments

min_offset

Minimum relative-time offset included in the grid.

max_offset

Maximum relative-time offset included in the grid.

width

Window duration in relative-time units. For example, with min_offset = -5, max_offset = 0, and width = 5, the window is labeled window_m05_z00 and covers the five relative-time units ending at the reference date. Use one value for a fixed-duration scan, such as width = 5. Use several values for a variable-duration scan, such as width = 2:4 or width = c(2, 4, 6).

slide_by

Number of relative-time units used when sliding the window start. A value of 1 creates consecutive starts; a value of 2 skips every other possible start.

type

Window-generation strategy. "fixed" creates one sliding window width. "variable" creates windows from all values in width. If width has more than one value, type is treated as "variable".

reference_col

Optional name of the reference timestamp column, such as "assessment_time" or "planting_time". This is stored as metadata on the returned window grid and used by window_pane() when its own reference_col argument is NULL.

Details

make_windows() does not place windows on calendar dates by itself. It defines the relative-time grid. If reference_col is supplied, that column name is stored with the grid so window_pane() can later place the windows relative to each row's site-specific reference date.

Value

A data frame with relative_start, relative_end, width, and label.

Examples

make_windows(min_offset = -7, max_offset = -1, width = 5)

make_windows(min_offset = -21, max_offset = -1, width = 5, slide_by = 3)

make_windows(min_offset = -7, max_offset = -1, width = 5, reference_col = "planting_time")

make_windows(
  min_offset = -5,
  max_offset = 5,
  width = c(2, 4, 6),
  slide_by = 2
)

Multivariable condition summary functions

Description

These functions create summaries from expressions evaluated in a weather window data frame. They are used inside the special .conditions entry of statistics.

Usage

count_when(condition, na.rm = TRUE)

proportion_when(condition, na.rm = TRUE)

sum_when(variable, condition, na.rm = TRUE)

mean_when(variable, condition, na.rm = TRUE)

max_when(variable, condition, na.rm = TRUE)

min_when(variable, condition, na.rm = TRUE)

max_consecutive_when(condition, na.rm = TRUE)

spell_count_when(condition, na.rm = TRUE)

mean_spell_duration_when(condition, na.rm = TRUE)

max_spell_duration_when(condition, na.rm = TRUE)

Arguments

condition

An expression evaluated in the window data frame.

na.rm

If TRUE, missing values are ignored. For proportion functions, the denominator is the number of non-missing observations.

variable

A numeric column evaluated in the window data frame.

Value

A function marked as a windcut condition summary. It receives a data frame and returns one numeric value.

Examples

weather <- data.frame(temp = c(17, 20, 24), rh = c(88, 92, 95), rain = c(0, 1, 0))
count_when(temp >= 18 & temp <= 26 & rh >= 90)(weather)

statistics <- list(
  temp = list(mean = "mean"),
  .conditions = list(
    favorable_hours = count_when(temp >= 18 & temp <= 26 & rh >= 90)
  )
)

Plot FDA Difference Curves

Description

Plot FDA Difference Curves

Usage

plot_fda_difference(
  analysis,
  value_col,
  title = NULL,
  xlab = "Time",
  ylab = NULL,
  color = "#20262e"
)

Arguments

analysis

A windcut_fda_analysis object returned by run_fda_analysis().

value_col

Weather variable to plot.

title

Plot title.

xlab

Label for the x-axis.

ylab

Label for the y-axis.

color

Line color.

Value

A ggplot2 object.


Plot FDA Retained Intervals

Description

Plot FDA Retained Intervals

Usage

plot_fda_intervals(
  analysis,
  alpha = NULL,
  show_none = TRUE,
  title = "Retained FDA intervals",
  xlab = "Time"
)

Arguments

analysis

A windcut_fda_analysis object returned by run_fda_analysis().

alpha

Optional significance levels to plot. If NULL, all alpha values stored in analysis are shown.

show_none

Logical; if TRUE, labels variables with no retained interval.

title

Plot title.

xlab

Label for the x-axis.

Value

A ggplot2 object.


Plot FDA Mean Curves

Description

Plot FDA Mean Curves

Usage

plot_fda_means(
  analysis,
  value_col,
  title = NULL,
  xlab = "Time",
  ylab = NULL,
  legend_title = "Group",
  palette = NULL
)

Arguments

analysis

A windcut_fda_analysis object returned by run_fda_analysis().

value_col

Weather variable to plot.

title

Plot title.

xlab

Label for the x-axis.

ylab

Label for the y-axis.

legend_title

Legend title for the grouping variable.

palette

Optional named vector of colors.

Value

A ggplot2 object.


Plot FDA Corrected P-Values

Description

Plot FDA Corrected P-Values

Usage

plot_fda_p_values(
  analysis,
  value_col,
  alpha = NULL,
  title = NULL,
  xlab = "Time",
  ylab = "Corrected p-value"
)

Arguments

analysis

A windcut_fda_analysis object returned by run_fda_analysis().

value_col

Weather variable to plot.

alpha

Significance levels to show as horizontal reference lines. If NULL, all alpha values stored in analysis are shown.

title

Plot title.

xlab

Label for the x-axis.

ylab

Label for the y-axis.

Value

A ggplot2 object.


Plot Functional Differences Between Two Groups

Description

Creates a ggplot2 visualization from the difference table produced by functional_group_summary(). The plotted values reflect the smoothing method chosen when that summary object was created.

Usage

plot_functional_difference(
  summary,
  title = "Functional difference between groups",
  xlab = "Time",
  ylab = "Difference",
  color = "#20262e",
  highlight_intervals = NULL
)

Arguments

summary

A list returned by functional_group_summary() or a data frame with time and difference columns.

title

Plot title.

xlab

Label for the x-axis.

ylab

Label for the y-axis.

color

Line color.

highlight_intervals

Optional data frame with start and end columns used to shade one or more intervals.

Value

A ggplot2 object.


Plot Smoothed Functional Means by Group

Description

Creates a ggplot2 visualization from the output of functional_group_summary(). The plotted values reflect the smoothing method chosen when that summary object was created.

Usage

plot_functional_means(
  summary,
  title = "Functional mean curves by group",
  xlab = "Time",
  ylab = "Mean value",
  legend_title = "Group",
  palette = NULL,
  highlight_intervals = NULL
)

Arguments

summary

A list returned by functional_group_summary() or a data frame with group, time, and mean_value columns.

title

Plot title.

xlab

Label for the x-axis.

ylab

Label for the y-axis.

legend_title

Legend title for the grouping variable.

palette

Optional named vector of colors.

highlight_intervals

Optional data frame with start and end columns used to shade one or more intervals.

Value

A ggplot2 object.


Plot Function-on-Scalar Coefficient Functions

Description

Extracts coefficient functions and approximate confidence bands from a fitted refund::pffr() model and returns a faceted ggplot2 visualization.

Usage

plot_functional_on_scalar(
  model,
  ci_level = 0.95,
  title = "Function-on-scalar coefficient functions",
  xlab = "Time",
  ylab = "Coefficient function",
  highlight_intervals = NULL
)

Arguments

model

A fitted pffr model returned by functional_on_scalar() or directly by refund::pffr().

ci_level

Confidence level used to form approximate pointwise bands.

title

Plot title.

xlab

Label for the x-axis.

ylab

Label for the y-axis.

highlight_intervals

Optional data frame with start and end columns used to shade one or more intervals.

Value

A faceted ggplot2 object.


Plot a Window-Pane Grid

Description

Visualizes candidate relative-time windows created by make_windows(). The vertical dashed line marks the reference date. Windows fully before the reference, fully after the reference, and crossing the reference are colored separately so the timing logic is visible.

Usage

plot_window_pane(
  windows,
  max_windows = 30,
  color_by = c("timing", "width", "none"),
  title = "Window-pane grid",
  subtitle = NULL,
  xlab = "Time relative to reference date",
  ylab = "Candidate window",
  reference_label = "Reference date"
)

Arguments

windows

A data frame created by make_windows().

max_windows

Maximum number of windows to display. Use Inf to show all rows.

color_by

Character value controlling segment color. Use "timing" to color windows by position relative to the reference date, "width" to color by window duration, or "none" for one color.

title

Plot title.

subtitle

Plot subtitle. If NULL, a subtitle is generated from the selected color_by value.

xlab

X-axis label.

ylab

Y-axis label.

reference_label

Label used for the vertical line at relative-time 0.

Value

A ggplot2 object.

Examples

windows <- make_windows(min_offset = -14, max_offset = 35, width = 7, slide_by = 7)
plot_window_pane(windows)

variable_windows <- make_windows(min_offset = -21, max_offset = -1, width = c(3, 5, 7))
plot_window_pane(variable_windows, color_by = "width")

Run a Functional Data Analysis Workflow

Description

Runs the main FDA workflow for one or more weather variables: creates subject-by-time matrices, computes smoothed group means, compares two groups with interval-wise permutation tests, and stores tidy summaries for plotting and feature extraction.

Usage

run_fda_analysis(
  data,
  id_col,
  time_col,
  group_col,
  value_cols,
  value_labels = NULL,
  alpha = 0.05,
  n_permutations = 1000,
  smooth_method = c("spline", "lowess", "none"),
  smooth_args = list(),
  time_grid = NULL,
  n_time_grid = 300,
  reference_group = NULL,
  comparison_group = NULL,
  quiet = TRUE,
  min_interval_length = 1
)

Arguments

data

A data frame in long format.

id_col

Subject identifier column.

time_col

Time column, such as relative day or days after planting.

group_col

Grouping column with exactly two groups.

value_cols

Weather variable columns to analyze.

value_labels

Optional named character vector or data frame with variable and label columns used for plot labels.

alpha

One or more significance levels used to extract intervals from the same set of corrected permutation p-values for each variable.

n_permutations

Number of permutations used by the interval-wise test.

smooth_method

Smoothing method used for group mean curves. One of "none", "lowess", or "spline".

smooth_args

Named list of extra arguments passed to the smoothing method.

time_grid

Optional grid for plotting smoothed group means. If NULL, a dense grid is created from the observed time range.

n_time_grid

Number of points in the dense plotting grid when time_grid = NULL.

reference_group

Optional reference group. If NULL, the first group level or first observed group is used.

comparison_group

Optional comparison group. If NULL, the other group is used.

quiet

Logical; if TRUE, suppresses routine console output emitted by fdatest::ITP2bspline().

min_interval_length

Minimum number of consecutive tested time points required for an interval to be retained. For daily series, this is the minimum number of consecutive days. Defaults to 1, which retains every run that crosses the corrected p-value threshold. This post-test filter does not alter the corrected p-values.

Value

A windcut_fda_analysis object with matrices, summaries, interval-test results, and tidy interval summaries.


Scan Candidate Weather Windows Relative to a Reference Time

Description

For each candidate window, subsets the weather series relative to a reference time and computes summary features. The reference can be an assessment date, planting date, flowering date, inoculation date, or any other biologically meaningful timestamp.

Usage

scan_windows(
  weather,
  reference_time,
  windows,
  weather_cols,
  time_col = "time",
  unit = c("days", "hours"),
  statistics
)

Arguments

weather

A weather data frame.

reference_time

Reference time used to place the candidate windows.

windows

A data frame created by make_windows().

weather_cols

Required character vector of existing numeric weather columns. Column names must be unique, non-missing, and non-empty. If named, every entry must have a unique, non-missing, non-empty output alias; .conditions is reserved. No columns are inferred. Use character() explicitly for condition-only summaries.

time_col

Name of the weather timestamp column.

unit

Time unit for relative-time windows. One of "days" or "hours".

statistics

Required summary specification. Use a non-empty character vector to apply the same statistics to all weather_cols, such as c("mean", "sd", "IQR"). Alternatively, use a named list keyed by every selected column's output alias (or column name when unnamed), with no unknown keys. Each entry must be a non-empty character vector or a nested named list of functions or single function names, for example list(temp = list(avg = "mean", spread = stats::sd)). Statistic names must be unique, non-missing, and non-empty. No summaries are inferred. The optional .conditions entry is a named list of multivariable condition summaries such as count_when(temp >= 18 & rh >= 90).

Details

The configured time column cannot be selected in weather_cols. Summary names must not collide with window metadata. An empty window grid is returned unchanged after validating the explicit summary specification.

Value

A data frame with one row per candidate window and summary metrics.


Screen Pairwise Correlations Among Candidate Features

Description

Computes pairwise correlations among numeric candidate predictors and suggests a reduced set of variables for modeling workflows that should avoid strongly correlated features. This is useful after window_pane() creates many metric-window columns.

Usage

screen_feature_correlations(
  data,
  feature_cols = NULL,
  exclude_cols = NULL,
  method = c("pearson", "spearman", "kendall"),
  threshold = 0.8,
  use = "pairwise.complete.obs"
)

Arguments

data

A data frame containing candidate feature columns.

feature_cols

Optional character vector of feature columns to compare. If NULL, all numeric columns are considered except exclude_cols.

exclude_cols

Columns to exclude when feature_cols = NULL, such as identifiers, assessment times, or response variables.

method

Correlation method passed to stats::cor(). One of "pearson", "spearman", or "kendall".

threshold

Absolute correlation threshold used to flag highly correlated feature pairs.

use

Missing-data handling passed to stats::cor().

Details

The selection heuristic is intentionally simple and transparent. For every pair with absolute correlation greater than or equal to threshold, the function removes the variable with the larger mean absolute correlation to all other candidate variables. This favors keeping variables that are less redundant overall.

Value

A list with:

correlation_matrix

Feature-by-feature correlation matrix.

high_correlations

Data frame of feature pairs with absolute correlation greater than or equal to threshold.

suggested_features

Character vector of features suggested to keep.

removed_features

Character vector of features suggested for removal.

feature_summary

Data frame with each feature's mean absolute correlation and suggested decision.

Examples

weather <- simulate_weather_series(
  days = 40,
  n_series = 8,
  id_col = "site_id",
  seed = 1
)
assessments <- simulate_assessment_data(weather, id_col = "site_id", seed = 1)
windows <- make_windows(min_offset = -10, max_offset = -1, width = 3)
features <- window_pane(
  weather = weather,
  assessments = assessments,
  windows = windows,
  reference_col = "assessment_time",
  id_col = "site_id",
  response_col = "disease_intensity",
  weather_cols = c("temp", "rh", "rain", "leaf_wetness"),
  statistics = list(temp = c("mean", "min", "max"), rh = "mean",
                    rain = "sum", leaf_wetness = "sum")
)

correlation_screen <- screen_feature_correlations(
  features,
  exclude_cols = c("site_id", "assessment_time", "disease_intensity"),
  method = "spearman",
  threshold = 0.8
)
correlation_screen$suggested_features

Screen Window-Derived Features Against a Disease Response

Description

Computes univariate associations between weather features produced by window_pane and a disease response. This implements the screening step commonly used after window-pane feature construction, where each metric-window summary is related to the response using a correlation coefficient and the resulting p-values are adjusted for multiple testing.

Usage

screen_window_features(
  data,
  response_col,
  feature_cols = NULL,
  method = c("spearman", "pearson"),
  adjust_method = "BH"
)

Arguments

data

A data frame that includes the response column and feature columns.

response_col

Name of the response column.

feature_cols

Optional character vector of feature columns to test. If NULL, all numeric columns except the response are screened.

method

Correlation method passed to stats::cor.test(). One of "spearman" or "pearson".

adjust_method

Method used by stats::p.adjust() to correct p-values.

Value

A data frame with feature names, parsed metric/window labels, correlation estimates, raw p-values, adjusted p-values, and sample size.


Simulate One Disease Assessment per Weather Series

Description

Creates one synthetic disease assessment for each weather time series. In the usual use case, each time series represents one location, plot, or experimental unit, and the assessment is measured once at the end of that series. The simulated response can be binary, ordinal, or a 0–100 percent severity value.

Usage

simulate_assessment_data(
  weather,
  id_col = NULL,
  response_type = c("percent", "binary", "ordinal"),
  n_levels = 10,
  seed = NULL,
  id_prefix = "A",
  time_col = "time",
  response_col = "disease_intensity"
)

Arguments

weather

A weather data frame with at least the standard windcut columns.

id_col

Optional column identifying independent weather series, such as locations. If NULL, the whole weather table is treated as one series.

response_type

Type of disease response to simulate. One of "binary", "ordinal", or "percent".

n_levels

Number of ordinal classes when response_type = "ordinal". For example, n_levels = 10 returns scores from 0 to 9.

seed

Optional random seed for reproducibility.

id_prefix

Prefix used to label assessments when id_col = NULL.

time_col

Name of the weather time column.

response_col

Name of the simulated response column.

Details

Disease risk is generated from interpretable weather summaries over each series: cumulative rain, mean relative humidity, mean temperature, and the proportion of wet observations. The result is intended for examples, tutorials, and tests rather than biological inference.

Value

A data frame with one row per weather series. It includes the series identifier, assessment time, response type, and simulated disease response.

Examples

weather <- simulate_weather_series(days = 30, seed = 1)
simulate_assessment_data(weather, response_type = "binary", seed = 1)

site_weather <- simulate_weather_series(
  days = 30,
  n_series = 4,
  id_col = "site_id",
  seed = 1
)

simulate_assessment_data(
  site_weather,
  id_col = "site_id",
  response_type = "ordinal",
  n_levels = 10,
  seed = 1
)

Simulate a Weather Time Series

Description

Creates a synthetic hourly weather series with diurnal temperature and humidity cycles, intermittent rain, and leaf wetness periods. This is useful for examples, tutorials, tests, and method development before field data are available.

Usage

simulate_weather_series(
  start = as.POSIXct("2024-01-01 00:00:00", tz = "UTC"),
  days = 60,
  n_series = 1,
  seed = NULL,
  id_col = NULL,
  id_prefix = "S",
  temp_mean = 22,
  temp_amp = 6,
  rh_mean = 80,
  rh_amp = 12,
  rain_prob = 0.08,
  tz = "UTC"
)

Arguments

start

Start timestamp for the simulation.

days

Number of days to simulate.

n_series

Number of independent weather series to generate.

seed

Optional random seed for reproducibility.

id_col

Optional name of the series identifier column. If NULL and n_series > 1, the output uses "series_id".

id_prefix

Prefix used when constructing simulated series identifiers.

temp_mean

Baseline temperature.

temp_amp

Amplitude of the diurnal temperature cycle.

rh_mean

Baseline relative humidity.

rh_amp

Amplitude of the diurnal relative humidity cycle.

rain_prob

Probability of rain in each hour.

tz

Time zone assigned to the simulated timestamps.

Value

A data frame with hourly weather observations.


Consecutive spell summary functions

Description

These functions summarize runs of consecutive observations that satisfy a condition. Missing values break sequences when na.rm = TRUE.

Usage

max_consecutive_above(threshold, na.rm = TRUE)

max_consecutive_at_or_above(threshold, na.rm = TRUE)

max_consecutive_below(threshold, na.rm = TRUE)

max_consecutive_at_or_below(threshold, na.rm = TRUE)

max_consecutive_between(lower, upper, inclusive = TRUE, na.rm = TRUE)

spell_count_above(threshold, na.rm = TRUE)

spell_count_at_or_above(threshold, na.rm = TRUE)

spell_count_below(threshold, na.rm = TRUE)

spell_count_between(lower, upper, inclusive = TRUE, na.rm = TRUE)

mean_spell_duration_above(threshold, na.rm = TRUE)

max_spell_duration_above(threshold, na.rm = TRUE)

Arguments

threshold

A single finite numeric threshold.

na.rm

If TRUE, missing values are ignored. For proportion functions, the denominator is the number of non-missing observations.

lower, upper

Single finite numeric limits. lower must be less than or equal to upper.

inclusive

If TRUE, values equal to the boundary are included.

Value

A function that takes a numeric vector and returns one numeric value.

Examples

max_consecutive_above(2)(c(1, 3, 4, 1, 5, 6, 7))
spell_count_above(2)(c(1, 3, 4, 1, 5, 6, 7))

Summarise Weather Inside a Single Window

Description

Computes a small set of epidemiology-friendly summaries from a subset of a weather time series.

Usage

summarise_weather_window(weather, weather_cols, statistics)

Arguments

weather

A validated weather data frame.

weather_cols

Required character vector of existing numeric weather columns. Column names must be unique, non-missing, and non-empty. If named, every entry must have a unique, non-missing, non-empty output alias; .conditions is reserved. No columns are inferred. Use character() explicitly for condition-only summaries.

statistics

Required summary specification. Use a non-empty character vector to apply the same statistics to all weather_cols, such as c("mean", "sd", "IQR"). Alternatively, use a named list keyed by every selected column's output alias (or column name when unnamed), with no unknown keys. Each entry must be a non-empty character vector or a nested named list of functions or single function names, for example list(temp = list(avg = "mean", spread = stats::sd)). Statistic names must be unique, non-missing, and non-empty. No summaries are inferred. The optional .conditions entry is a named list of multivariable condition summaries such as count_when(temp >= 18 & rh >= 90).

Value

A one-row data frame with summary metrics.


Thermal-time summary functions

Description

These functions summarize heat accumulation from temperature vectors. ⁠degree_days_*()⁠ divides degree-hours by 24 and therefore assumes hourly input data. For daily data, use ⁠degree_hours_*()⁠ only if each row already represents the desired time step.

Usage

degree_hours_above(base, na.rm = TRUE)

degree_hours_below(base, na.rm = TRUE)

degree_days_above(base, na.rm = TRUE)

degree_days_below(base, na.rm = TRUE)

thermal_time_above(base, na.rm = TRUE)

thermal_time_between(lower, upper, na.rm = TRUE)

hours_in_temperature_range(lower, upper, inclusive = TRUE, na.rm = TRUE)

proportion_in_temperature_range(lower, upper, inclusive = TRUE, na.rm = TRUE)

Arguments

base

A single finite numeric base temperature.

na.rm

If TRUE, missing values are ignored. For proportion functions, the denominator is the number of non-missing observations.

lower, upper

Single finite numeric limits. lower must be less than or equal to upper.

inclusive

If TRUE, values equal to the boundary are included.

Value

A function that takes a numeric vector and returns one numeric value.

Examples

degree_hours_above(10)(c(8, 10, 12, 15))
thermal_time_between(18, 26)(c(16, 20, 30))

Threshold-based summary functions

Description

These functions create summary functions for use inside the statistics argument of summarise_weather_window(), scan_windows(), and window_pane(). Each function returns a closure that is applied to a numeric vector from one weather variable.

Usage

count_above(threshold, na.rm = TRUE)

count_at_or_above(threshold, na.rm = TRUE)

count_below(threshold, na.rm = TRUE)

count_at_or_below(threshold, na.rm = TRUE)

count_between(lower, upper, inclusive = TRUE, na.rm = TRUE)

proportion_above(threshold, na.rm = TRUE)

proportion_at_or_above(threshold, na.rm = TRUE)

proportion_below(threshold, na.rm = TRUE)

proportion_at_or_below(threshold, na.rm = TRUE)

proportion_between(lower, upper, inclusive = TRUE, na.rm = TRUE)

Arguments

threshold

A single finite numeric threshold.

na.rm

If TRUE, missing values are ignored. For proportion functions, the denominator is the number of non-missing observations.

lower, upper

Single finite numeric limits. lower must be less than or equal to upper.

inclusive

If TRUE, values equal to the boundary are included.

Value

A function that takes a numeric vector and returns one numeric value.

Examples

count_above(30)(c(28, 31, 33, NA))
count_between(18, 26)(c(17, 18, 22, 27))
proportion_at_or_above(90)(c(88, 91, 95, NA))

statistics <- list(
  temp = list(hours_18_26 = count_between(18, 26)),
  rh = list(prop_humid = proportion_at_or_above(90))
)

Validate a Weather Time Series

Description

Checks that a weather table contains the expected columns, converts the time column to POSIXct, sorts observations by time, and removes duplicated timestamps.

Usage

validate_weather_data(
  weather,
  time_col = "time",
  required_cols = c("temp", "rh", "rain", "leaf_wetness")
)

Arguments

weather

A data frame with weather observations.

time_col

Name of the timestamp column.

required_cols

Character vector of required weather columns.

Value

A cleaned data frame sorted by time.


Derive meteorological variables

Description

These functions add biologically useful variables to a weather data frame. Column arguments are supplied unquoted. The original data frame is returned with one additional column.

Usage

derive_dew_point(data, temp, rh, name = "dew_point")

derive_vpd(data, temp, rh, name = "vpd")

derive_temperature_range(data, tmax, tmin, name = "temp_range")

derive_leaf_wetness_from_rh(
  data,
  rh,
  threshold = 90,
  name = "leaf_wetness_est"
)

derive_leaf_wetness_from_rh_temp(
  data,
  rh,
  temp,
  rh_threshold = 90,
  temp_range = NULL,
  name = "leaf_wetness_est"
)

derive_favorable_condition(data, condition, name = "favorable")

Arguments

data

A data frame.

temp, rh, tmax, tmin

Columns in data.

name

Name of the new column.

threshold, rh_threshold

Numeric threshold used to create binary wetness or favorability variables.

temp_range

Optional numeric vector of length two. When supplied, estimated leaf wetness is one only when RH is high and temperature is inside this range.

condition

A logical expression evaluated in data.

Details

derive_dew_point() uses the Magnus approximation with constants a = 17.625 and b = 243.04. derive_vpd() computes saturation vapor pressure from temperature and actual vapor pressure from relative humidity. Relative humidity is interpreted as percent from 0 to 100, and VPD is returned in kPa. Dew point is returned as NA_real_ when relative humidity is zero because the logarithmic Magnus approximation has no finite value at zero.

Value

A data frame with the new derived column.

Examples

weather <- data.frame(temp = c(20, 24), rh = c(85, 95), rain = c(0, 1))

weather |>
  derive_dew_point(temp, rh) |>
  derive_vpd(temp, rh) |>
  derive_leaf_wetness_from_rh(rh, threshold = 90)

Weather-specific summary functions

Description

These functions provide readable names for common epidemiological summaries. The units of names such as rainy_days() and wet_days() depend on the time resolution of the input data. With hourly data they count hours; with daily data they count days.

Usage

humid_hours(threshold = 90, na.rm = TRUE)

dry_hours(threshold = 60, na.rm = TRUE)

proportion_humid(threshold = 90, na.rm = TRUE)

proportion_dry(threshold = 60, na.rm = TRUE)

max_consecutive_humid_hours(threshold = 90, na.rm = TRUE)

max_consecutive_dry_hours(threshold = 60, na.rm = TRUE)

rainy_hours(threshold = 0, na.rm = TRUE)

rainy_days(threshold = 0, na.rm = TRUE)

rain_events(threshold = 0.2, na.rm = TRUE)

rain_event_count(threshold = 0.2, na.rm = TRUE)

max_rain_event(threshold = 0.2, na.rm = TRUE)

mean_rain_event(threshold = 0.2, na.rm = TRUE)

hours_since_last_rain(threshold = 0.2, na.rm = TRUE)

days_since_last_rain(threshold = 0.2, na.rm = TRUE)

wet_hours(threshold = 0, na.rm = TRUE)

wet_days(threshold = 0, na.rm = TRUE)

proportion_wet(threshold = 0, na.rm = TRUE)

max_consecutive_wet_hours(threshold = 0, na.rm = TRUE)

wet_spell_count(threshold = 0, na.rm = TRUE)

mean_wet_spell_duration(threshold = 0, na.rm = TRUE)

max_wet_spell_duration(threshold = 0, na.rm = TRUE)

Arguments

threshold

A single finite numeric threshold.

na.rm

If TRUE, missing values are ignored. For proportion functions, the denominator is the number of non-missing observations.

Value

A function that takes a numeric vector and returns one numeric value.

Examples

humid_hours()(c(85, 91, 96))
rain_events(0.2)(c(0, 0.3, 0.4, 0, 1.2))

Build a Wide Feature Table from Weather Windows

Description

Applies scan_windows() to many site-specific reference dates and returns a wide table with one row per reference event and one column per metric-window combination. The reference date can be an assessment date, planting date, or any other timestamp stored in the input table.

Usage

window_pane(
  weather,
  assessments,
  windows,
  reference_col = NULL,
  id_col = NULL,
  response_col = NULL,
  weather_cols,
  time_col = "time",
  unit = c("days", "hours"),
  statistics
)

Arguments

weather

A weather data frame.

assessments

A data frame containing reference times and optional IDs or responses.

windows

A data frame created by make_windows().

reference_col

Name of the reference timestamp column. If NULL, the function uses metadata stored by make_windows() or falls back to "assessment_time".

id_col

Optional site, location, or assessment identifier column. When this column is present in both weather and assessments, each row is matched to the weather series from the same ID.

response_col

Optional response column, such as disease intensity.

weather_cols

Required character vector of existing numeric weather columns. Column names must be unique, non-missing, and non-empty. If named, every entry must have a unique, non-missing, non-empty output alias; .conditions is reserved. No columns are inferred. Use character() explicitly for condition-only summaries.

time_col

Name of the weather timestamp column.

unit

Time unit for relative-time windows. One of "days" or "hours".

statistics

Required summary specification. Use a non-empty character vector to apply the same statistics to all weather_cols, such as c("mean", "sd", "IQR"). Alternatively, use a named list keyed by every selected column's output alias (or column name when unnamed), with no unknown keys. Each entry must be a non-empty character vector or a nested named list of functions or single function names, for example list(temp = list(avg = "mean", spread = stats::sd)). Statistic names must be unique, non-missing, and non-empty. No summaries are inferred. The optional .conditions entry is a named list of multivariable condition summaries such as count_when(temp >= 18 & rh >= 90).

Details

Configured time, ID, reference, and response columns cannot be selected in weather_cols. Empty assessment tables are rejected.

Value

A wide data frame with one row per reference event.


Demo Data for Window-Pane Workflows

Description

A bundled dataset for the getting-started, window-pane, and feature-screening tutorials.

Format

A list with three components:

weather

Daily weather data for multiple simulated sites, all with the same time-series length and at least 30 days before planting.

weather_hourly

Hourly weather data used to create weather.

assessments

One disease assessment per site, including assessment_time, planting_time, and disease_intensity.

Details

The data were generated with simulate_weather_series and simulate_assessment_data and then saved as package data so the main workflow tutorials can begin directly with analysis.