serial_difference: Calculate the difference between sequential observations

View source: R/rates_of_change.R

serial_differenceR Documentation

Calculate the difference between sequential observations

Description

This function provides a quick method to calculate the duration between sequential observations. The function is based on difference which can calculate the difference between numeric objects or time stamps (i.e. Dates or DateTimeClasses).

Usage

serial_difference(x, na.rm = FALSE, ...)

Arguments

x

A vector of numbers or time stamps (i.e. Dates or DateTimeClasses) supported by difftime.

na.rm

A logical input defining whether or not to remove NAs from the output vector. If FALSE, the last value is NA because a difference cannot be calculated between the final observation and the 'next' observation. If TRUE, this NA (and any other NAs) are removed.

...

Other arguments passed to difference. These include units (a character input specifying the units in which to return time differences) and f, a function to process differences.

Value

The function returns a vector of differences. Each value is the difference between one value and the next value in a sequence.

Author(s)

Edward Lavender

Examples

#### Define some time series
d1 <- c(seq.POSIXt(as.POSIXct("2016-01-01"), as.POSIXct("2016-01-29"), by = "2 mins"),
        seq.POSIXt(as.POSIXct("2016-01-30"), as.POSIXct("2016-02-03"), by = "20 mins"),
        seq.POSIXt(as.POSIXct("2016-04-01"), as.POSIXct("2016-05-01"), by = "days")
        )
length(d1)

#### Example (1): Calculate the duration between observations
duration <- serial_difference(d1)
table(duration)
head(duration)
tail(duration) # The last value is NA

#### Example (2): Calculate the duration between observations in user-specified units
# ... by supplying the units argument, which is passed to difference() to and then to difftime()
duration <- serial_difference(d1, units = "mins")

#### Example (3): Implement post-processing by supplying f to difference()
serial_difference(d1, units = "days", f = function(x){round(as.numeric(x), 3)})

#### Example (4): Remove any NAs
duration <- serial_difference(d1, units = "days", na.rm = TRUE)
# The last value is no longer NA:
tail(duration)
# The sequence is one unit shorter than the input sequence due to the removal of the final NA:
length(d1) - length(duration)

#### Example (5) Numeric example
x <- c(seq(0, 10, by = 1), seq(11, 20, by = 0.1))
serial_difference(x)
serial_difference(x, na.rm = TRUE)


edwardlavender/Tools4ETS documentation built on Nov. 29, 2022, 7:41 a.m.