add_unit_id: Add unique unit IDs to time series

View source: R/add_unit_id.R

add_unit_idR Documentation

Add unique unit IDs to time series

Description

This function extracts unique unit (e.g., electronic tag) IDs from a dataframe containing unit attributes, termed dat_units, that correspond to units listed in a time series, termed dat_ts. This is useful when the same unit (e.g., an electronic tag) is deployed multiple times so that each 'unit' code (i.e., the code of a particular tag) does not correspond to a unique deployment. In this scenario, both the unit code and the time of deployment need to be included in the matching procedure to add unique unit IDs to the time series.

Usage

add_unit_id(dat_ts, dat_units)

Arguments

dat_ts

A dataframe comprising time series collected from 'units'. This must contain two named columns: 'timestamp', a vector which defines the time of each observation (in Date or DateTimeClasses format); and 'unit', a vector which defines the unit code (which may be non unique). The column 'unit' should also be found in dat_units (see below).

dat_units

A dataframe which contains unit metadata. This must contain four named columns: 'unit', as above for dat_ts; 'unit_id', a unique identifier for unit; 'start_time', a vector which defines the time of each unit's deployment; and 'end_time', a vector which defines the end of each unit's deployment. 'start_time' and 'end_time' should be of the same object type, and the same type as 'timestamp' in dat_ts.

Value

The function returns a vector of unit IDs, as defined in the dat_units$unit_id column, which correspond to each observation in the dat_ts dataframe.

Author(s)

Edward Lavender

Examples

#### Define example data
# In this example, we have two units, but one has been re-deployed:
dat_units <- data.frame(unit = c(1, 1, 2),
                        unit_id = c(1, 2, 3),
                        start_time = as.POSIXct(c("2016-01-01", "2016-01-02", "2016-01-01")),
                        end_time = as.POSIXct(c("2016-01-02", "2016-01-03", "2016-01-02"))
                        )
# Our observational dataframe contains units but not unique unit IDs:
dat_ts <- data.frame(unit = c(1, 1, 2),
                     timestamp = as.POSIXct(c("2016-01-01 00:30:00",
                     "2016-01-02 00:30:00",
                     "2016-01-01 00:30:00"))
                     )

#### Example (1): Add unit IDs to the observational dataframe
# The first observation corresponds to unit_id 1;
# The second observation corresponds to the same unit
# ... but a different deployment, and has unit_id = 2
# The third observation corresponds to unit id 3;
dat_ts$unit_id <- add_unit_id(dat_ts, dat_units)
dat_ts


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