twa: Time Weighted Averages

View source: R/twa.R

twaR Documentation

Time Weighted Averages

Description

This function computes time weighted averages of value_var across zero or more groups. Averages can be computed by trapezoids or left/right endpoints. Time weighted averages can be computed with raw values or relative to a reference. Calculations can be above below, or about the supplied reference value. By default, they are computed as raw.

Usage

twa(
  df,
  value_var,
  time_var,
  ...,
  method = "trapezoid",
  ref = 0,
  ref_dir = "raw"
)

Arguments

df

a data frame, assumed to be in a 'long form' with time values in a single column

value_var

the value to be avaraged, a column within df

time_var

the time variable for weighting. Either POSIXct or numeric.

...

grouping variables within df

method

method to compute TWA, one of c('trapezoid', 'left', 'right')

ref

a value to compute the TWA relative to

ref_dir

the direction to compute the average relative to ref, one of c('raw', 'above', 'below', 'about')

Details

If multiple rows have the same grouping variables and time, the median value will be selected. Rows with missing. If only one value within a grouping level is supplied, that value will be returned.d twa also computes the total time elapsed, the largest and smallest gap between consecutive points, and the number of values received, used, and omitted. When time_var is POSIXct, twa will default to minutes.

Value

a data frame containing any grouping variables, the computed twa, and some other summary statistics

Note

Need to check out this behavior as the behavior of summarize on grouped dataframes changed with dplyr 1.0 >:(

Author(s)

Sven Halvorson

Examples

start_date = lubridate::ymd_hms('2019-01-01 00:00:00')
time_dat = tibble::tibble(id = c(1, 1, 1, 1, 2, 2),
                          val = c(4, 6, 8, 6, 1, NA),
                          t = lubridate::minutes(c(0, 10, 15, 45, 0, 10)) + start_date,
                          t2 = 1:6)
twa(df = time_dat, value_var = val, time_var = t, id)
twa(df = time_dat, value_var = val, time_var = t2, method = 'left', ref = 7, ref_dir = 'below')

svenhalvorson/SvenR documentation built on Aug. 25, 2023, 1:31 p.m.