Learn R Programming

cliot (version 1.0.0)

calculate_tir: Calculate Time in Target Range (TIR)

Description

Calculates the Time in Target Range (TIR) as the percentage of valid data points that fall inclusively within a specified minimum and maximum target value. This function is designed to be robust, including checks for non-numeric input and invalid range definitions.

Usage

calculate_tir(data_vector, target_min, target_max)

Value

A numeric value between 0 and 100 representing the calculated TIR percentage. If an input error is detected, the function returns a character string containing a helpful error message.

Arguments

data_vector

A numeric vector of values (e.g., sensor readings, clinical measurements) to analyze.

target_min

A single numeric value defining the minimum boundary of the target range (inclusive).

target_max

A single numeric value defining the maximum boundary of the target range (inclusive).

Details

The function enforces strict input validation:

  • Checks that data_vector, target_min, and target_max are numeric.

  • Ensures target_min is not greater than target_max.

  • NA values within data_vector are automatically excluded from the calculation of both the numerator (in-range count) and the denominator (total count).

The TIR is calculated as: \((\frac{\text{Count in Range}}{\text{Total Valid Count}}) \times 100\).

Examples

Run this code

#1. Successful Calculation

glucose_data <- c(125, 95, 150, 88, 110, 105, 78, 133, 99, 101, 140)
min_target <- 90
max_target <- 130
calculate_tir(glucose_data, min_target, max_target) # Expected: 72.72727

#2. Handling NA values (Points are 100, 110, 80, 120, 150. 3 of 5 are in range.)

na_data <- c(100, NA, 110, 80, 120, NA, 150)
calculate_tir(na_data, 90, 130) # Expected: 60

#3. Error Handling: Non-numeric data

calculate_tir(c("A", 100, 110), 90, 130)

#4. Error Handling: Invalid target range

calculate_tir(glucose_data, 130, 90)

#5. Edge Case: Empty vector

calculate_tir(numeric(0), 90, 130)

Run the code above in your browser using DataLab