---
title: "Getting Started with windcut"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Getting Started with windcut}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[UTF-8]{inputenc}
---
**Version:** This tutorial uses windcut 0.2.1.
It uses `aggregate_to_daily()` and reads the feature table from
`window_pane(...)$features`. In 0.1.0, use `aggregate_weather_daily()`;
`window_pane()` returns the feature table directly.
With 0.1.0 installed, run `vignette("getting-started", package = "windcut")`
for the matching tutorial.
```{r setup, include=FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
message = FALSE,
warning = FALSE,
fig.width = 7,
fig.height = 4.5,
fig.alt = "ggplot2 chart showing weather data preparation or window-pane feature generation."
)
```
```{r packages, message=FALSE, warning=FALSE}
library(windcut)
library(dplyr)
library(ggplot2)
library(tidyr)
library(cowplot)
```
`windcut` starts from a simple idea: each field, site, plot, or location has a
weather time series and one biologically meaningful reference date. The
reference date can be an assessment date, planting date, flowering date,
inoculation date, or any other date that makes sense for the disease system.
What you will learn. This tutorial shows how to organize your
own data for `windcut`, how to check the expected structure, and how to turn
weather records into window-pane predictors.
## The two tables windcut expects
Most workflows use two tables. The weather table has repeated observations over
time. The assessment table has one row per modeling unit, usually one row per
site or field.
| Table | Required information | Typical columns |
|---|---|---|
| Weather table | Site identifier, observation time, and one or more numeric weather variables | `site_id`, `time`, `daily_mean_temp`, `daily_mean_rh`, `daily_sum_rain` |
| Assessment table | Site identifier, at least one reference date, and optionally a disease response | `site_id`, `assessment_time`, `planting_time`, `disease_intensity` |
The exact weather-variable names are your choice. `windcut` can summarize
columns named `daily_mean_temp`, `temp2m`, `relhum`, `prectot`, `sradiation`, or
any other clear names. The important part is that you tell the function which
columns should be summarized.
## Use the demo data as a template
The bundled dataset is useful as a template because it has the same structure
expected from a real project: one daily weather table and one disease assessment
table.
```{r}
data(window_pane_demo_data)
weather <- window_pane_demo_data$weather
assessments <- window_pane_demo_data$assessments
weather |>
slice_head(n = 6) |>
knitr::kable()
assessments |>
slice_head(n = 6) |>
knitr::kable()
```
The weather table is long: each site appears on many dates. The assessment
table is short: each site appears once because the disease outcome is observed
once for each weather series.
```{r}
data_structure <- data.frame(
table = c("weather", "assessments"),
rows = c(nrow(weather), nrow(assessments)),
unique_sites = c(n_distinct(weather$site_id), n_distinct(assessments$site_id))
)
knitr::kable(data_structure)
```
## Check your own weather table
Before making windows, check four things in your own weather table:
1. The site identifier is present and has the same name or meaning as the
identifier in the assessment table.
2. The time column is a `Date` or `POSIXct` column.
3. Weather variables are numeric.
4. Each site has records that cover the windows you want to summarize.
The demo data already meet those requirements. The code below shows the type of
check that is useful when you replace the demo data with your own table.
```{r}
weather_check <- weather |>
summarise(
first_date = min(time),
last_date = max(time),
sites = n_distinct(site_id),
missing_temp = sum(is.na(daily_mean_temp)),
missing_rh = sum(is.na(daily_mean_rh))
)
knitr::kable(weather_check)
```
If your source data are hourly, aggregate them before using daily windows. The
aggregation function lets you choose the time column, the site column, the
weather columns, and the statistics used to create daily variables.
```{r}
hourly_weather <- window_pane_demo_data$weather_hourly
daily_from_hourly <- aggregate_to_daily(
weather = hourly_weather,
id_col = "site_id",
time_col = "time",
value_cols = c("temp", "rh", "rain", "leaf_wetness"),
statistics = list(
temp = c("mean", "min", "max"),
rh = "mean",
rain = list(sum = "sum"),
leaf_wetness = list(sum = "sum")
)
)
daily_from_hourly |>
slice_head(n = 6) |>
knitr::kable()
```
## Choose the reference date
The reference date is the point from which windows are counted. In this example
the reference is the disease assessment date, but the same logic works for a
planting date, flowering date, inoculation date, or another event. The reference
date can differ by site.
```{r}
assessments |>
select(site_id, planting_time, assessment_time, disease_intensity) |>
slice_head(n = 8) |>
knitr::kable()
```
Negative offsets are before the reference date. Positive offsets are after the
reference date. Offset `0` is the reference date itself.
```{r}
windows <- make_windows(
min_offset = -21,
max_offset = 0,
width = 7,
slide_by = 1,
reference_col = "assessment_time"
)
windows |>
slice_head(n = 8) |>
knitr::kable()
```
The plot shows the candidate windows that will be applied to each site. The
dashed line marks the reference date. Each segment is one 7-day weather period
that will be summarized.
```{r}
plot_window_pane(
windows,
max_windows = 12,
color_by = "none",
title = "Candidate windows before disease assessment",
subtitle = "The same relative-time grid is applied to each site-specific assessment date",
xlab = "Time relative to assessment date (days)",
ylab = NULL
) +
theme(axis.text.y = element_text(size = 8))
```
## Select the weather variables
Use the original names from your data unless you intentionally want shorter
feature names. Here the daily demo variables are summarized as they are named in
the table.
```{r}
daily_weather_cols <- c(
"daily_mean_temp",
"daily_mean_rh",
"daily_sum_rain",
"daily_sum_leaf_wetness"
)
```
The `statistics` argument controls what is calculated inside each window. You
can use ordinary R summaries such as `"mean"` and `"sum"`, and you can use
biological summary functions such as `count_between()` and `humid_hours()`.
```{r}
summary_statistics <- list(
daily_mean_temp = list(
mean = "mean",
days_18_26 = count_between(18, 26)
),
daily_mean_rh = list(
mean = "mean",
humid_days = humid_hours(90)
),
daily_sum_rain = list(
total = "sum",
rainy_days = rainy_days(0)
),
daily_sum_leaf_wetness = list(
wet_days = wet_days(0)
)
)
```
## Inspect one site before scaling up
Scanning one site first is a practical diagnostic. It lets you confirm that the
windows, reference date, selected weather columns, and summary functions produce
the expected columns.
```{r}
first_site <- assessments$site_id[1]
first_reference <- assessments$assessment_time[1]
single_site_scan <- scan_windows(
weather = weather |> filter(site_id == first_site),
reference_time = first_reference,
windows = windows,
weather_cols = daily_weather_cols,
statistics = summary_statistics
)$features
single_site_scan |>
select(label, daily_mean_temp_mean, daily_mean_temp_days_18_26,
daily_mean_rh_humid_days, daily_sum_rain_total) |>
slice_head(n = 8) |>
knitr::kable()
```
The weather plot below shows the same idea in time. The model-ready predictors
come from summaries of the weather values inside the candidate windows.
```{r}
plot_weather <- weather |>
filter(site_id == first_site) |>
filter(time >= first_reference - 21 * 86400, time <= first_reference)
ggplot(plot_weather, aes(time, daily_mean_temp)) +
geom_vline(
xintercept = first_reference,
linetype = "dashed",
color = "#20262e",
linewidth = 0.7
) +
geom_line(color = "#2b6c4f", linewidth = 0.8) +
labs(
title = "Weather history before the reference date",
subtitle = "The dashed line is the disease assessment date for one site",
x = NULL,
y = "Daily mean temperature (deg C)"
) +
theme_half_open()
```
## Build the feature table
`window_pane()` repeats the scan for each row in the assessment table. With
`id_col = "site_id"`, it uses only weather from the matching site. Both tables
must have this column, and every assessment site must have a matching weather
series. Use `$features` to get the modeling table with one row per assessment
and one column for each weather-summary-window combination. Use `$coverage`
to inspect missing percentages and observation counts separately.
```{r}
features <- window_pane(
weather = weather,
assessments = assessments,
windows = windows,
id_col = "site_id",
reference_col = "assessment_time",
response_col = "disease_intensity",
weather_cols = daily_weather_cols,
statistics = summary_statistics
)$features
feature_overview <- data.frame(
rows = nrow(features),
columns = ncol(features)
)
knitr::kable(feature_overview)
features |>
select(1:10) |>
slice_head(n = 6) |>
knitr::kable()
```
## Screen candidate features
After feature generation, the first screening question is whether each
window-derived variable is associated with the disease response. The screening
output ranks candidate features by correlation with disease intensity.
```{r}
screened <- screen_window_features(
data = features,
response_col = "disease_intensity",
method = "spearman"
)
screened |>
slice_head(n = 8) |>
knitr::kable()
```
The plot highlights the strongest candidate windows. These are not final model
results; they are a structured way to decide which timing periods deserve
closer modeling and validation.
```{r}
top_screened <- screened |>
mutate(abs_estimate = abs(estimate)) |>
arrange(desc(abs_estimate)) |>
slice_head(n = 8) |>
mutate(feature = factor(feature, levels = rev(feature)))
ggplot(top_screened, aes(abs_estimate, feature)) +
geom_col(fill = "#6ea87d") +
labs(
title = "Top screened windows",
x = "Absolute Spearman correlation",
y = NULL
) +
theme_half_open()
```
## Recommended workflow
1. Prepare a long weather table with one row per site and time point.
2. Prepare an assessment table with one row per site and the reference date.
3. Choose candidate windows that match the biological question.
4. Use interpretable summaries for weather exposure.
5. Inspect one site before applying the workflow to the full dataset.
6. Screen and validate candidate predictors before using them in final models.