Skip to contents

The as.data.frame method for "sts" objects cbinds the following slots into a wide data frame (one row per observation time): observed, epoch, state, alarm, upperbound, populationFrac (as population), freq, and epochInPeriod.

The tidy.sts function additionally reshapes multivariate time series into the long format (one row per time \(\times\) unit), adding a unit column as well as the useful epoch transformations year, epochInYear, and date. The tidy format is particularly useful for regression models or plotting functions.

Usage

tidy.sts(x, ...)

# S3 method for class 'sts'
as.data.frame(x, ..., tidy = FALSE, as.Date = x@epochAsDate)

Arguments

x

an object of class "sts".

...

unused (argument of the generic).

tidy

logical indicating if tidy.sts should be called.

as.Date

logical indicating if epoch should be of class "Date". Ignored in the tidy case, where epoch remains numeric and an extra column date is added.

Value

a data frame combining slots of the "sts" input.

For as.data.frame, the number of rows equals the number of time points, nrow(x), and there are two special columns:

freq

for weekly or daily data and if x@epochAsDate is TRUE, the number of samples in the current year, otherwise x@freq.

epochInPeriod

the epoch fraction within the current year, epochInYear(x)/freq.

For tidy.sts, the resulting data frame has one row for each combination of epoch and unit, the latter a factor with levels the colnames(x). It contains the above special columns plus the following extra time variables:

year

numeric, from year(x).

epochInYear

numeric, the day/week/month number (or, more generally, “cycle” within x@freq), from epochInYear(x).

date

"Date", from epoch(x, as.Date=TRUE) if possible, otherwise NA (for non-standard frequency(x) if x@epochAsDate is false).

Author

Sebastian Meyer

Examples

data("momo")
momo

momolong <- tidy.sts(momo)
head(momolong, 3)
str(momolong)

momowide <- as.data.frame(momo)
str(momowide, vec.len = 2)  # unit-specific columns, like "sts" matrix slots
stopifnot(nrow(momowide) == nrow(momo))

## tidy.sts() is the same as as.data.frame(<sts>, tidy = TRUE)
stopifnot(identical(as.data.frame(momo, tidy = TRUE), momolong))