Package 'birdnetTools'

Title: R package for working with BirdNET output
Description: What the package does (one paragraph).
Authors: Sunny Tseng [aut, cre] (ORCID: <https://orcid.org/0000-0002-8621-2244>)
Maintainer: Sunny Tseng <[email protected]>
License: MIT + file LICENSE
Version: 0.1.1
Built: 2026-12-03 02:25:55 UTC
Source: https://github.com/birdnet-team/birdnetTools

Help Index


Add datetime-related columns from BirdNET output filenames

Description

Extracts and parses datetime information from filenames in the file path column (automatically detected), then adds several useful time-related columns (e.g., date, year, month, hour) to the input data frame. Several common formats are tried by default, and users can supply their own with formats (see Details).

Usage

birdnet_add_datetime(
  data,
  formats = c("%Y%m%dT%H%M%S", "%Y%m%d%H%M%S", "%Y%m%d_%H%M%S",
    "%Y%m%d_%H%M", "%d%m%Y_%H%M%S", "%m%d%Y_%H%M%S"),
  tz = "UTC",
  quiet = FALSE
)

Arguments

data

A data frame containing BirdNET output.

formats

A character vector of datetime formats, using the same codes as strptime() (see Details). Formats are tried in order, and the first one that successfully parses a file name is used. Defaults to common year-first formats, plus day-first and month-first variants. See Details for how ambiguous dates are handled.

tz

A character string specifying the time zone to assign when parsing datetime. Defaults to "UTC".

quiet

Logical. If TRUE, suppresses the status messages about how many file names were parsed, failed, or were ambiguous. Warnings are still shown. Defaults to FALSE.

Details

Defining your own formats. If the default formats don't match your file names, supply a format for each pattern in your data.

Supported codes:

  • ⁠%Y⁠: 4-digit year (1900-2099)

  • ⁠%y⁠: 2-digit year

  • ⁠%m⁠: 2-digit month

  • ⁠%d⁠: 2-digit day

  • ⁠%H⁠, ⁠%M⁠, ⁠%S⁠: 2-digit hour, minute, second

Any other characters (such as ⁠_⁠, -, or T) are matched literally. For example, ⁠site1_2024-06-15_0530.wav⁠ needs formats = "%Y-%m-%d_%H%M".

Ambiguous dates. The defaults include both day-first (⁠%d%m%Y⁠) and month-first (⁠%m%d%Y⁠) formats. A file name such as ⁠05062023_133500⁠ is valid as both, so the format listed first (day-first) is used and a message lists the rows to check. If your data uses only one convention, supply that format on its own to avoid the ambiguity.

Value

A data frame with additional columns:

datetime

POSIXct datetime parsed from the filename.

date

Date portion of the datetime.

year

Year of detection.

month

Month of detection.

mday

Day of the month.

yday

Day of the year.

hour

Hour of the day.

minute

Minute of the hour.

Rows whose file names can't be parsed get NA in all of these columns. Existing columns with these names are overwritten, with a warning. If all of these columns already exist, the data is returned unchanged.

Examples

## Not run: 
birdnet_add_datetime(example_jprf_2023) |>
glimpse()

## End(Not run)

Add site column from BirdNET output filenames

Description

Extracts a specific directory level from the file path column (automatically detected) to act as a site identifier, then adds a site column to the input data frame. By default the whole directory name is used, but formats lets you keep only part of it, such as the letters or the digits (see Details).

Usage

birdnet_add_site(data, i = -2, formats = ".*", quiet = FALSE)

Arguments

data

A data frame containing BirdNET output.

i

An integer specifying the index of the path element to extract when split by slashes. Defaults to -2, which corresponds to the immediate parent directory of the file (e.g., extracting "Site-A" from "path/to/Site-A/audio.wav"). Negative values count from the right-hand side.

formats

A character vector of regular expressions (as used by stringr::str_extract()) that describe which part of the extracted directory name to keep as the site. Expressions are tried in order, and the first one that matches is used. Defaults to ".*", which keeps the whole directory name. See Details.

quiet

Logical. If TRUE, suppresses the status messages about how many file names were successfully matched to a site or could not be matched. Defaults to FALSE

Details

Keeping only part of the name. If your folder names combine several pieces of information, supply a regular expression that matches only the part you want. For a folder named Pine05:

  • ".*" (default): "Pine05" (the whole name)

  • "^[A-Za-z]+": "Pine" (the letters at the start only)

  • "[0-9]+": "05" (the digits only)

Value

A data frame with an additional column:

site

The extracted directory or folder name (or the part of it matched by formats) used as the site identifier.

Examples

## Not run: 
combined_data <- birdnet_combine("path/to/BirdNET/output")
data_with_site <- birdnet_add_site(combined_data, i = -2)

# keep only the letters of the folder name (e.g. "Pine05" becomes "Pine")
birdnet_add_site(combined_data, formats = "^[A-Za-z]+")

# keep only the digits (e.g. "Pine05" becomes "05")
birdnet_add_site(combined_data, formats = "[0-9]+")

## End(Not run)

Calculate species-specific confidence thresholds for BirdNET detections

Description

Computes species-specific confidence thresholds for BirdNET detections using either a target precision or a target predicted probability from a logistic regression model. The function returns one threshold per species. The precision-based approach follows Tseng et al. (2025), while the probability-based method is adapted from Wood and Kahl (2024).

Usage

birdnet_calc_threshold(
  validated_data,
  full_data = NULL,
  probability = NULL,
  precision = NULL
)

Arguments

validated_data

A data frame of validated BirdNET detections with columns common_name, confidence, and validation. The validation column must contain 1 (true positives) and 0 (false positives).

full_data

Optional. A data frame of all BirdNET detections with at least common_name and confidence columns. If NULL, validated_data is used instead.

probability

Numeric. A target predicted probability (between 0 and 1) used to calculate thresholds from the logistic regression model.

precision

Numeric. A target precision (between 0 and 1) used to select the lowest threshold that achieves the desired precision.

Details

You must supply exactly one of precision or probability. If both or neither are provided, the function will throw an error.

When using the precision method, the function predicts probabilities for each detection using a logistic regression model fit to validated_data. It then identifies the lowest confidence threshold that meets or exceeds the target precision.

When using the probability method, the function calculates the confidence threshold corresponding to the inverse logit of the target predicted probability from the regression model.

All thresholds are clamped to fall between the minimum observed confidence in validated_data and 1. If the target cannot be reached for a species (for example, if the model predicts a precision below the target at every confidence score), its threshold is NA and a message says so.

Value

A tibble with two columns:

common_name

Species common name.

threshold

The calculated confidence threshold for that species, or NA if the target cannot be reached.

References

Tseng, S., Hodder, D. P., & Otter, K. A. (2025). Setting BirdNET confidence thresholds: Species-specific vs. universal approaches. Journal of Ornithology. https://doi.org/10.1007/s10336-025-02260-w Wood, C. M., & Kahl, S. (2024). Guidelines for appropriate use of BirdNET scores and other detector outputs. Journal of Ornithology. https://doi.org/10.1007/s10336-024-02144-5


Combine BirdNET output files from a directory

Description

Reads and combines multiple BirdNET output .csv or .txt files from a specified directory (including subdirectories) into a single data frame.

Usage

birdnet_combine(path, add_filepath = FALSE)

Arguments

path

Character string. Path to a directory containing BirdNET output files.

add_filepath

Logical. If TRUE, adds a column filepath to the output data frame indicating the source file for each row. Use with caution: if the input files already contain a column named filepath, it will be overwritten. Default is FALSE.

Details

Files named "analysis_params" or "CombinedTable" are automatically excluded. Files that are empty or cannot be read are skipped. A summary of how many files were successfully read and which files (if any) caused errors is printed at the end.

This function is useful for aggregating large batches of BirdNET results without requiring consistent formatting. All subdirectories are searched recursively. Files are read using readr::read_delim(), and empty files are silently ignored.

If no valid files are found, or if all files are excluded or cause read errors, the function aborts with an informative message.

Value

A data frame combining all readable BirdNET .csv or .txt files found in the directory. The column structure depends on the input files and is not standardized by this function.

See Also

readr::read_delim(), list.files()

Examples

## Not run: 
# Combine all BirdNET output files in a directory and its subfolders
data <- birdnet_combine(path = "path/to/BirdNET/output", add_filepath = FALSE)

# View a few rows of the result
head(data)

## End(Not run)

Generate Detection History Matrix, Effort Matrix, and Summary for Occupancy Modeling

Description

Summarizes BirdNET detection data across specified survey intervals (occasions), filters sites based on minimal detection persistence thresholds, and aligns them with operational effort data. Returns a zero-filled site-by-occasion binary matrix, an identical matching matrix documenting sampling effort intensity for modeling detection probability covariates, and a detailed long-format data frame summary.

Usage

birdnet_detection_history(
  data,
  effort_data,
  survey_interval,
  i = -2,
  min_unique_days = 1
)

Arguments

data

A data frame containing BirdNET detections, including column matches for filepaths and prediction confidence scores.

effort_data

A data frame containing monitoring operational effort, requiring at least site and date columns to indicate the active monitoring windows and locations of each ARU device. Users can generate this via birdnet_get_effort(), which derives effort data from a directory of audio files by defining a site-date combination as "active" if at least one recording exists. If an n_files column is present, file counts will be aggregated per survey occasion block.

survey_interval

A character string specifying the temporal unit for grouping survey occasions (e.g., "1 day", "1 week", "7 days"). Passed directly to lubridate::floor_date().

i

An integer specifying the path hierarchy index for extracting site IDs. Passed directly to birdnet_add_site. Defaults to -2.

min_unique_days

An integer specifying the threshold of unique calendar days a site must possess raw detections on to be kept. Sites with detections spanning fewer than min_unique_days are dropped early from compilation. Defaults to 1.

Details

The function groups continuous temporal data into distinct survey blocks using lubridate::floor_date(). Detections are cross-referenced against your effort_data: occasions where monitoring effort occurred but no target species were detected are explicitly zero-filled. If an ARU was not operational during a specific time block, it is preserved as an NA value in the detection history to ensure structural integrity for missing-visit designs.

Values greater than 0 in the final detection matrix are collapsed to 1 to format the output for binary presence/absence occupancy models (e.g., spOccupancy, unmarked).

Value

A named list containing three components:

detection_history

A numeric base R matrix where rows represent unique sites (assigned as row names), columns represent chronological temporal occasions, and cells indicate binary occupancy integers (1, 0, or NA for missing effort).

effort_matrix

A numeric base R matrix matching the exact dimensions and sorting order of detection_history. If n_files was present in the effort data, cells represent total file counts per site-occasion. Otherwise, cells contain binary integers indicating presence (1) or absence (0) of operational effort.

detection_summary

A data frame in long format containing the underlying aggregated metrics per site/occasion, including detection counts (n_detections), maximum verification confidence (max_conf), and the file path of the highest confidence detection (max_conf_audio).


Extract audio clips for BirdNET detections

Description

Cuts a short audio clip for each detection in a BirdNET output table and saves all clips in one folder, for example to validate detections without needing the original recordings. Each clip runs from the start of the detection to its end, plus a buffer before and after.

Usage

birdnet_extract_clips(
  data,
  output_dir,
  audio_dir = NULL,
  buffer = 3,
  file = NULL,
  overwrite = FALSE,
  quiet = FALSE
)

Arguments

data

A data frame containing BirdNET output, with columns for the file path, start time, end time, species common name, and confidence (detected automatically).

output_dir

Character. Folder where the clips are saved. It is created if it does not exist.

audio_dir

Character or NULL. Folder containing the original audio recordings, searched including subfolders. Only used for files that are not found at the path stored in data. Defaults to NULL, which uses the stored paths only.

buffer

Numeric. Seconds added before the start and after the end of each detection. Defaults to 3.

file

Character or NULL. Where to save the table as a CSV file (must end in .csv). Defaults to NULL, which saves it as detections_clips.csv in output_dir, next to the clips.

overwrite

Logical. If FALSE, the function stops before extracting anything when the table file already exists, so that a table you have already validated is not replaced by accident. Defaults to FALSE.

quiet

Logical. If TRUE, suppresses the status messages about how many clips were extracted or could not be created. Defaults to FALSE.

Details

The detection table, with the clip columns added (see Value), is saved as a CSV file in the same folder, so the folder holds everything needed to validate the detections.

File names. Clips are saved in the same audio format as the original recording (e.g. WAV stays WAV, MP3 stays MP3) and are named ⁠<ID>_<recording name>_<start>_<end>_<species common name>_<confidence>.<extension>⁠, where:

  • ID is the row number of the detection in data, with leading zeros (01, 02, ...), so the clips sort in the same order as the table.

  • start and end are the detection times in seconds (without the buffer).

  • the species common name has characters that are unsafe in file names replaced with ⁠_⁠.

  • confidence is the detection confidence, rounded to three decimals.

For example, ⁠01_20230518_133500_12_15_Barred_Owl_0.873.wav⁠. Because every name starts with its own ID, names are always unique.

Finding the audio. For each detection, the function first uses the file path stored in the table. If that file no longer exists (for example because the recordings were moved to another drive), it looks for a file with the same name inside audio_dir, including all subfolders. If several files have that name, the one whose parent folders best match the original path is used.

Clips near the edges. A clip is trimmed to fit inside the recording, so a detection near the start or end of a file gets a shorter buffer on that side. The times actually used are returned in clip_start and clip_end.

Value

The input data frame with additional columns:

clip_file

The name of the clip file in output_dir, or NA if the clip could not be created.

clip_start

Start of the clip in the original recording, in seconds.

clip_end

End of the clip in the original recording, in seconds.

See Also

birdnet_subsample(), birdnet_launch_validation()

Examples

## Not run: 
sampled <- birdnet_subsample(my_data, n = 100, seed = 1)

clips <- birdnet_extract_clips(
  sampled,
  output_dir = "validation_audio",
  audio_dir = "path/to/recordings",
  buffer = 3
)
# "validation_audio" now holds the clips and detections_clips.csv

## End(Not run)

Filter BirdNET output data by species, confidence, date, and time

Description

Applies one or more common filtering operations to a BirdNET output data frame. Supports filtering by species name, confidence threshold (universal or species-specific), year, date range, and hour of day.

Usage

birdnet_filter(
  data,
  species = NULL,
  threshold = NULL,
  year = NULL,
  min_date = NULL,
  max_date = NULL,
  hour = NULL
)

Arguments

data

A data frame containing BirdNET output. Relevant columns (e.g., ⁠common name⁠, confidence, datetime) are automatically detected by birdnet_detect_columns.

species

Character vector. One or more common names of species to retain (e.g., c("Swainson's Thrush", "American Robin")).

threshold

Either a single numeric value between 0 and 1 (for a universal threshold), or a data frame with columns common_name and threshold for species-specific thresholds.

year

Integer or vector of integers specifying year(s) to retain (e.g., 2024:2025).

min_date, max_date

Optional. Character strings or Date objects specifying a date range in "YYYY-MM-DD" format. If only one is provided, filtering is open-ended on the other side.

hour

Integer vector between 0 and 23 specifying hours of the day to retain (e.g., 4:7).

Details

This function uses birdnet_detect_columns to automatically identify the relevant columns (e.g., for species names, confidence, datetime) based on common naming patterns.

All applied filter parameters are stored as an attribute called "filter_log" attached to the returned data frame, which can be accessed via attr(x, "filter_log").

Value

A filtered data frame with an attribute "filter_log" containing the applied filters.

Examples

## Not run: 
filtered <- birdnet_filter(
  data = birdnet_combine("path/to/output"),
  species = "Swainson's Thrush",
  threshold = 0.75,
  year = 2025,
  min_date = "2025-06-01",
  hour = 4:8
)
attr(filtered, "filter_log")

## End(Not run)

Calculate recording effort by site and date

Description

Scans a directory for all audio files, extracts site and datetime metadata from their paths/filenames, and returns a unique timeline of recording effort with file counts.

Usage

birdnet_get_effort(path, i = -2)

Arguments

path

A character string specifying the path to the directory containing the audio files.

i

An integer specifying the index of the path element to extract as the site identifier when split by slashes. Defaults to -2, which corresponds to the immediate parent directory of the file, passed directly to birdnet_add_site(). Negative values count from the right-hand side.

Details

The function identifies audio files matching common extensions, automatically detects site names via birdnet_add_site(), parses dates via birdnet_add_datetime(), and reduces the output to a unique combination of sites and dates, summarizing total files recorded.

Value

A tibble (data frame) with three columns:

site

The extracted site identifier.

date

The date on which recording effort occurred.

n_files

Integer. The total number of audio files recorded at that site on that specific date.

Examples

## Not run: 
effort_df <- birdnet_get_effort("path/to/audio/storage", i = -2)
head(effort_df)

## End(Not run)

Create a heatmap of BirdNET detections by hour and date

Description

Generates a heatmap visualizing the daily activity pattern of a specified species detected in BirdNET output data. The heatmap shows detection counts by hour and date, optionally filtered by species, confidence threshold, date range, and hours of the day.

Usage

birdnet_heatmap(
  data,
  species = NULL,
  threshold = NULL,
  min_date = NULL,
  max_date = NULL,
  hour = NULL
)

Arguments

data

A data frame containing BirdNET output. Must include columns like common_name, confidence, and filepath.

species

Character scalar or vector specifying the common name(s) of species to visualize. If NULL, no species filtering is applied.

threshold

Either a numeric scalar between 0 and 1 (applied uniformly), or a data frame with columns common_name and threshold for species-specific values. If NULL, no threshold filtering is applied.

min_date

Optional character scalar giving the earliest date to include ("YYYY-MM-DD" format).

max_date

Optional character scalar giving the latest date to include ("YYYY-MM-DD" format).

hour

Optional numeric (typically integer) vector of hours (0–23) to include in the heatmap.

Value

A ggplot object showing a heatmap of detection counts by date (x-axis) and hour (y-axis). Fill color corresponds to the number of detections per date-hour combination.

Examples

## Not run: 
birdnet_heatmap(
  data = birdnet_output,
  species = "Swainson's Thrush",
  threshold = 0.7,
  min_date = "2024-06-01",
  max_date = "2024-06-30",
  hour = 4:7
)

## End(Not run)

Launch the BirdNET audio validation app

Description

Starts an interactive Shiny application for manually validating BirdNET detections using audio clips and spectrograms. This tool is designed to support manual review of BirdNET results.

Usage

birdnet_launch_validation()

Details

This function launches a Shiny app for validating detections one by one. The recommended workflow is:

  1. Subsample detections with birdnet_subsample(),

  2. Cut audio clips with birdnet_extract_clips(),

  3. Launch this app and select the folder that contains the clips and the table.

In the app you can view the spectrogram and play the audio of each detection, and edit its validation. Changes are saved to the table in the folder after every edit, so you can stop and resume at any time.

Value

A shiny.appobj that runs the BirdNET audio validation platform in a web browser.

See Also

birdnet_validation_ui, birdnet_validation_server

Examples

## Not run: 
birdnet_launch_validation()

## End(Not run)

Subsample BirdNET detections by species

Description

Draws a subsample of n detections from a BirdNET output data frame, for example for manual validation. Sampling is done across all rows of data. To subsample one species, filter to that species first (see Examples). Four methods are available: even or proportional stratified sampling across confidence score bins, simple random sampling, or the highest-confidence detections. Optionally saves the subsample to a CSV file.

Usage

birdnet_subsample(
  data,
  n,
  method = c("even_stratified", "proportional_stratified", "random", "top"),
  bin_width = 0.05,
  seed = NULL,
  save_to_file = FALSE,
  file = NULL,
  quiet = FALSE
)

Arguments

data

A data frame containing BirdNET output.

n

Integer. Total number of detections to subsample. If data has n or fewer rows, all rows are returned.

method

Character. Subsampling method to use. One of:

"even_stratified"

Samples evenly across confidence score bins. Bins with too few detections contribute all they have, and the remainder is shared among the other bins.

"proportional_stratified"

Samples across confidence score bins in proportion to the number of detections in each bin.

"random"

Simple random sample of n detections.

"top"

The n detections with the highest confidence.

Defaults to "even_stratified".

bin_width

Numeric. Width of the confidence score bins used by the stratified methods. Defaults to 0.05.

seed

Integer or NULL. If given, the subsample is reproducible. The random number generator state of your session is left unchanged.

save_to_file

Logical. If TRUE, saves the output to a CSV file. Defaults to FALSE. Automatically set to TRUE if file is provided.

file

Character or NULL. File path to save the output CSV. If NULL and save_to_file = TRUE, saves as "subsampled_data.csv" in the working directory.

quiet

Logical. If TRUE, suppresses the status messages about how many detections were returned and whether all of them were kept because data had no more than n rows. Defaults to FALSE.

#' @details Choosing a method.

  • "random" gives an unbiased sample, suited to estimating overall precision.

  • "even_stratified" gives balanced coverage across confidence scores, suited to relating precision to score or choosing a threshold.

  • "proportional_stratified" mirrors the confidence distribution of the detections, so it is dominated by low-confidence detections.

  • "top" is useful for confirming that a species is present, but it is biased for estimating precision.

Several species. Sampling is not done per species. To subsample each species separately, apply the function to each species in turn (see Examples).

Value

A data frame containing the subsampled observations.

Examples

## Not run: 
# one species: filter first, then subsample
my_data |>
  dplyr::filter(common_name == "Barred Owl") |>
  birdnet_subsample(n = 100, method = "even_stratified", seed = 1)

# several species: apply the function to each one
my_data |>
  split(my_data$common_name) |>
  purrr::map(birdnet_subsample, n = 100) |>
  dplyr::bind_rows()

## End(Not run)

Example monitoring effort table from John Prince Research Forest

Description

A sample operational effort table mapping the active recording history of Autonomous Recording Units (ARUs) deployed across 5 sites in John Prince Research Forest, British Columbia, Canada, during May–June 2023. This data documents the baseline monitoring effort, where a given location and date combination is associated with an active ARU device if one or more audio files were successfully recorded.

Usage

effort_jprf_2023

Format

effort_jprf_2023

A data frame with rows and columns detailing active recording days. Key columns include:

site

Character string indicating the unique identifier for the ARU deployment location

date

Date object representing the calendar day of monitoring effort

n_files

Integer representing the total number of audio files recorded at that location on that day

Details

This dataset acts as the operational counterpart to example_jprf_2023 and is useful for demonstrating workflow alignment between species detections and true field effort, specifically for zero-filling non-detections in occupancy modeling.

This dataset was generated directly using the birdnet_get_effort() function. For more details on the generation parameters, data constraints, and internal file processing pipelines, please refer to the function documentation.

Source

https://sunnytseng.ca/


Example BirdNET selection table from John Prince Research Forest

Description

A sample BirdNET selection table generated from audio recordings collected from 5 sites, in John Prince Research Forest, British Columbia, Canada, during May–June 2023. Recordings were scheduled continuously over 24 hours using a duty cycle of 1 minute on, 4 minutes off. Audio files were analyzed using the BirdNET GUI (model version 2.4) with a confidence threshold of 0.1; all other parameters were kept at their default values.

Usage

example_jprf_2023

Format

example_jprf_2023

A data frame with 392,300 rows and 14 columns. Key columns include:

filepath

Full path to the audio file from which the detection was made

start

Start time of the detection in seconds

end

End time of the detection in seconds

scientific_name

Scientific name of the detected species or sound event

common_name

Common name of the detected species or sound event

confidence

BirdNET-assigned confidence score (0 to 1)

lat

Latitude of the recording location (set to -1 if not embedded)

lon

Longitude of the recording location (set to -1 if not embedded)

week

Week number of the year (set to -1 if not available)

overlap

Whether overlapping segments were analyzed (0 = no, 1 = yes)

sensitivity

Sensitivity parameter used during detection (default = 1)

min_conf

Minimum confidence threshold used during detection (e.g., 0.1)

species_list

Species list constraint used (e.g., "None" if not set)

model

Name of the BirdNET model used for detection

Details

This dataset is useful for demonstrating typical BirdNET output and testing workflows involving species filtering, thresholding, and temporal subsetting.

Source

https://sunnytseng.ca/