View source: R/rates_of_change.R
serial_difference | R Documentation |
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
).
serial_difference(x, na.rm = FALSE, ...)
x |
A vector of numbers or time stamps (i.e. |
na.rm |
A logical input defining whether or not to remove NAs from the output vector. If |
... |
Other arguments passed to |
The function returns a vector of differences. Each value is the difference between one value and the next value in a sequence.
Edward Lavender
#### 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.