R/mt_join_time.R

Defines functions get_unique_names standardize_window_units check_reused_y warn_multiple_matches mt_join_time

Documented in mt_join_time

#' Join values onto a move2 object by closest timestamp
#'
#' @description
#' Joins a `move2` object with a data.frame, matching on track id and timestamp.
#' Values can be matched with the closest overall timestamp, the closest
#' timestamp before or after each timestamp, or by an exact match (a standard
#' join).
#'
#' The join will always use the [mt_track_id_column()] and
#' [mt_time_column()] of the input `move2` as the track id and timestamp,
#' respectively. To join on different columns, set them beforehand with
#' [mt_set_track_id_column()] and/or [mt_set_time_column()].
#'
#' @param x A `move2` object.
#' @param y A data.frame containing columns with track id and timestamp
#'   information.
#' @param ... Additional join conditions passed to [dplyr::join_by()] that
#'   further restrict which records in `y` may match each record in `x`.
#' @param method How to match timestamps during the join. Matches are only made
#'   within the same track and among `y` records that satisfy the conditions in
#'   `...`.
#'   - `"closest"` (default) matches each record in `x` to the record in `y`
#'     with the closest timestamp.
#'   - `"closest_before"` matches each record in `x` to the record in `y` with
#'     the closest timestamp that is at or before the timestamp in `x`.
#'   - `"closest_after"` matches each record in `x` to the record in `y` with
#'     the closest timestamp that is at or after the timestamp in `x`.
#'   - `"exact"` matches records that have the exact same timestamp.
#' @param window Maximum time difference
#'   allowed between a record in `x` and its matched record in `y`. If no
#'   timestamps in `y` fall within this window for a given `x`, then no values
#'   are joined to that record. By default, no window restriction is applied.
#'
#'   If `mt_time(x)` is a date or datetime, `window` should be provided
#'   with time units (e.g. `units::set_units(1, "s")`). If `mt_time(x)` is
#'   numeric, `window` should also be numeric.
#' @param track_id_column_y Name of the column containing the track IDs in `y`.
#'   By default, uses the same name as the track id column in `x`.
#' @param time_column_y Name of the column containing the timestamps in `y`.
#'   By default, uses the same name as the time column in `x`.
#' @param suffix_y Suffix appended to column names from `y` to disambiguate them
#'   from column names that also exist in `x`, if needed (for instance, if `x`
#'   and `y` share the same track id and timestamp column names).
#' @param multiple How to handle rows in `x` that have multiple matches in `y`
#'   (that is, when multiple `y` records are equidistant to a given `x` record).
#'   - `"all"` (default) keeps all matches. `x` records with multiple matches
#'     are duplicated for each matching `y` record. No data is lost. This option
#'      allows you to decide later about which records to use (for instance,
#'      based on data quality). allows you to make an informed decisions what
#'      records to use based on data quality later. Setting the argument
#'      explicitly prevents being warned about duplications of records.
#'   - `"first"` keeps only the match that comes first in `y`'s row order.
#'   - `"last"` keeps only the match that comes last in `y`'s row order.
#'
#'   Note that `"first"` and `"last"` determine which matches to keep using
#'   the **row order** of `y`, *not* the time order. To have these options
#'   respect time order, first sort `y` by time.
#' @param on_reused_y What to do when a single record in `y` is matched to more
#'   than one record in `x`. Note that reusing `y` values may violate certain
#'   assumptions in later analyses.
#'   - `"warn"` (default) shows a warning.
#'   - `"error"` throws an error. Use this to ensure that every `y` record is
#'     present at most once in the output.
#'   - `"ignore"` includes reused records without a warning. Use this to
#'     suppress this warning if you expect reused `y` records.
#' @param na_matches Indicator for whether `NA` values should be considered to
#'   match. `"never"` (default) refuses to match records with `NA` values in
#'   any of the join columns. `"na"` matches missing values to each other.
#'   Note that setting `na_matches = "na"` can lead to a large increase in
#'   the number of rows in the output if many columns contain `NA` records.
#'
#' @return A `move2` containing all rows in `x` with additional columns and
#'   values from `y` attached. By default, rows in `x` that match
#'   multiple rows in `y` will appear multiple times in the output.
#'
#' @seealso [dplyr::left_join()]
#'
#' @details
#' ## Reused and duplicated records
#'
#' Note that `y` values may be reused during the join. That is, if the same `y`
#' record is nearest to multiple `x` records, then it will be matched to each of
#' those `x` records. You can mitigate this behavior by providing a `window`
#' to match only nearby records, but this does not fully prevent reuse
#' from occurring. To identify which values are reused, add a row identifier
#' column to `y` before joining and look for duplicated row IDs in the joined
#' output.
#'
#' By default, a warning is shown when `y` records are reused
#' in the output. If you expect `y` records to be reused, you can set
#' `on_reused_y = "ignore"`. To stop with an error instead, set
#' `on_reused_y = "error"`.
#'
#' Similarly, if a record in `x` is equally close to multiple records in `y`,
#' that record will appear multiple times in the joined output. This happens
#' when several records in `y` share the same timestamp or when the nearest `y`
#' records before and after an `x` record are the same distance away (for
#' `method = "closest"`). To instead ensure that only a single record is
#' matched in these cases, use the `multiple` argument to specify a selection
#' criterion.
#'
#' ## Type coercion of join key columns
#'
#' If any of the columns matched by equality have different object types in
#' `x` and `y`, the output column will be coerced to the common type of
#' `x` and `y`. For example, if the track id in `x` is a factor column and
#' the track id in `y` is a character column, the output column will be
#' character.
#'
#' @export
#'
#' @author Finn Roberts
#'
#' @examples
#' x <- mt_sim_brownian_motion(t = 1:5, tracks = c("a", "b"))
#' y <- data.frame(
#'   track = rep(c("a", "b"), each = 3),
#'   time = c(1.4, 2.7, 4.5, 0.5, 3, 4.2),
#'   sensor_value = 1:6
#' )
#'
#' # For each x record, attach the temporally closest y record
#' # Note that for multiple records in x the same record in y is the closest one
#' mt_join_time(x, y)
#'
#' # Restrict to only consider records before or after the `x` timestamp
#' mt_join_time(x, y, method = "closest_before")
#'
#' mt_join_time(x, y, method = "closest_after")
#'
#' # or to match on exact timestamp matches only
#' mt_join_time(x, y, method = "exact")
#'
#' # By default the closest match at any time gap is used. To only match if the
#' # `y` record is within a certain time difference, use `window`:
#' mt_join_time(x, y, window = 0.5)
#'
#' # `mt_join_time()` always matches using `x`'s designated track id and time
#' # column. If the `y` track and timestamps use different column names, you
#' # can provide them:
#' colnames(y) <- c("track_id", "timestamp", "sensor_value")
#' mt_join_time(
#'   x,
#'   y,
#'   track_id_column_y = "track_id",
#'   time_column_y = "timestamp"
#' )
#'
#' # If any `x` records are equally close to multiple `y` records, all matches
#' # are retained
#' y <- data.frame(
#'   track = c("a", "a", "b", "b"),
#'   time = c(2.5, 1.5, 3.5, 4.5),
#'   sensor_value = 1:4
#' )
#' mt_join_time(x, y)
#'
#' # Set `multiple` to select a single match in these cases
#' mt_join_time(x, y, multiple = "first")
#'
#' # `multiple` matches by `y` row order. If you want to match by time order,
#' # you must first sort `y` by time
#' y <- y[order(y$track, y$time), ]
#' mt_join_time(x, y, multiple = "first")
#'
#' # You can provide additional join criteria to further restrict the matched
#' # records. For instance, you may have data for multiple sensors:
#' x$sensor <- c("acc", rep("gps", 4), "acc", rep("gps", 4))
#'
#' # But other data may only be associated with a particular sensor:
#' y <- data.frame(
#'   track = c("a", "a", "a", "b", "b"),
#'   time = c(1.6, 3.6, 5.6, 2.6, 4.6),
#'   sensor = "gps",
#'   ndvi = c(0.62, 0.55, 0.44, 0.35, 0.42)
#' )
#'
#' # By default every record in x gets a match, including accelerometer records:
#' mt_join_time(x, y)
#'
#' # Additional match criteria ensure only the relevant records are considered,
#' # while retaining all `x` records:
#' mt_join_time(x, y, sensor == sensor)
mt_join_time <- function(
  x,
  y,
  ...,
  method = "closest",
  window = NULL,
  track_id_column_y = mt_track_id_column(x),
  time_column_y = mt_time_column(x),
  suffix_y = ".y",
  multiple = NULL,
  on_reused_y = "warn",
  na_matches = "never"
) {
  time_column_x <- mt_time_column(x)
  track_id_column_x <- mt_track_id_column(x)

  # Ensure a data.table y is treated as data.frame to avoid unexpected
  # data.table semantics
  if (inherits(y, "data.table")) {
    y <- as.data.frame(y)
  }

  method <- rlang::arg_match(
    method,
    c(
      "closest_before",
      "closest_after",
      "closest",
      "exact"
    )
  )

  # If no explicit `multiple` is set, behavior is same as `"all"`, but we warn
  # if duplicate matches are detected. Setting it explicitly silences warning.
  warn_multiple <- is.null(multiple)
  if (warn_multiple) {
    multiple <- "all"
  }

  # dplyr also supports "any", but it doesn't add much in our case and by
  # omitting we can avoid reimplementing it ourselves for `method = "closest"`
  multiple <- rlang::arg_match(multiple, c("all", "first", "last"))
  on_reused_y <- rlang::arg_match(on_reused_y, c("warn", "error", "ignore"))

  if (!rlang::is_scalar_character(suffix_y)) {
    cli_abort(
      "{.arg suffix_y} should be a character length 1.",
      class = "move2_error_join_suffix"
    )
  }

  suffix <- c("", suffix_y)

  if (method == "closest") {
    # here we run the function recursively to ensure consistent behaviour and
    # then select the correct records
    row_id_column_x <- get_unique_names("row_id", x, y)
    row_id_column_y <- get_unique_names("row_id_y", y, x, row_id_column_x)

    x <- x |> tibble::add_column(!!row_id_column_x := seq_len(nrow(x)))
    y <- y |> tibble::add_column(!!row_id_column_y := seq_len(nrow(y)))

    before <- mt_join_time(
      x,
      y,
      method = "closest_before",
      ...,
      suffix_y = suffix_y,
      track_id_column_y = track_id_column_y,
      time_column_y = time_column_y,
      window = window,
      multiple = multiple,
      on_reused_y = "ignore",
      na_matches = na_matches
    )
    after <- mt_join_time(
      x,
      y,
      method = "closest_after",
      ...,
      suffix_y = suffix_y,
      track_id_column_y = track_id_column_y,
      time_column_y = time_column_y,
      window = window,
      multiple = multiple,
      on_reused_y = "ignore",
      na_matches = na_matches
    )
    time_y_column_in_x <- ifelse(
      paste0(time_column_y, suffix_y) %in% names(before),
      paste0(time_column_y, suffix_y),
      time_column_y
    )
    difftime_column <- get_unique_names("difftime", before, after)
    mt_stack(
      before |>
        tibble::add_column(
          !!difftime_column := mt_time(before) -
            dplyr::pull(before, time_y_column_in_x)
        ),
      after |>
        tibble::add_column(
          !!difftime_column := dplyr::pull(after, time_y_column_in_x) -
            mt_time(after)
        ),
      .track_combine = "merge"
    ) |>
      arrange(!!rlang::sym(row_id_column_x)) -> a

    # Per row_id select the rows with the smallest time difference, if all
    # differences within a row_id are NA all rows are retained. NA's are set to
    # Inf so all NA groups have a minimum of Inf
    v <- as.numeric(pull(a, difftime_column))
    v[is.na(v)] <- Inf
    sizes <- vctrs::vec_run_sizes(pull(a, row_id_column_x))
    g <- rep.int(seq_along(sizes), sizes)
    o <- order(g, v)
    grp_min <- v[o[!duplicated(g[o])]]
    s <- v == grp_min[g]
    # Only retain the first occurrence of each x/y row combination
    first <- vctrs::vec_duplicate_id(data.frame(
      pull(a, row_id_column_x),
      pull(a, row_id_column_y)
    ))
    joined <- a[first == seq_along(first) & s, ]

    # At this point we can still have equidistant before/after matches, so if
    # multiple != "all" we need to select the first/last of each of these.
    if (multiple != "all") {
      rx <- joined[[row_id_column_x]]
      ry <- joined[[row_id_column_y]]

      # Sort by x index order, then y index order (inverted for "last"),
      # select first instance of each x row, and reorder to original order
      o <- order(rx, if (multiple == "first") ry else -ry)
      joined <- joined[sort(o[!duplicated(rx[o])]), ]
    }

    if (warn_multiple) {
      warn_multiple_matches(joined[[row_id_column_x]])
    }
    check_reused_y(joined[[row_id_column_y]], on_reused_y)

    joined <- joined |>
      select(
        -any_of(c(
          difftime_column,
          row_id_column_x,
          row_id_column_y
        ))
      )

    rownames(joined) <- NULL # Reset rownames to 1:N

    return(joined)
  }

  # Ensure `window` is in the same scale as the diff of the values in the
  # timestamp column.
  window <- standardize_window_units(window, x[[time_column_x]])

  dots <- rlang::enexprs(...)
  track_x_sym <- rlang::sym(track_id_column_x)
  track_y_sym <- rlang::sym(track_id_column_y)
  time_x_sym <- rlang::sym(time_column_x)
  time_y_sym <- rlang::sym(time_column_y)

  temporal <- switch(
    method,
    closest_before = rlang::expr(closest(!!time_x_sym >= !!time_y_sym)),
    closest_after = rlang::expr(closest(!!time_x_sym <= !!time_y_sym)),
    exact = rlang::expr(!!time_x_sym == !!time_y_sym)
  )

  # Add window conditions that bound the accepted matches to within a certain
  # timeframe. `join_by()` requires that columns are precomputed, so we generate
  # a temporary column to store the window limits for each `x`.
  window_col <- get_unique_names(".window", x, y)

  if (!is.null(window) && method %in% c("closest_before", "closest_after")) {
    window_sym <- rlang::sym(window_col)

    if (method == "closest_before") {
      x[[window_col]] <- x[[time_column_x]] - window
      window_cond <- list(rlang::expr(!!window_sym <= !!time_y_sym))
    } else {
      x[[window_col]] <- x[[time_column_x]] + window
      window_cond <- list(rlang::expr(!!window_sym >= !!time_y_sym))
    }
  } else {
    window_cond <- list()
  }

  # Temporary row index for x so we can identify rows that got multiple matches
  row_x_col <- get_unique_names("row_x", x, y)
  x[[row_x_col]] <- seq_len(nrow(x))

  # Temporary row index for y so we can identify y's that matched multiple x
  row_y_col <- get_unique_names("row_y", y, x, row_x_col)
  y[[row_y_col]] <- seq_len(nrow(y))

  # The temporal condition is listed last so that dplyr resolves the nearest
  # match within each group created by track, window limits, and any additional
  # matching criteria. Otherwise, dplyr matches closest timestamps first and
  # then drops the records if the match does not satisfy the other conditions.
  join_spec <- rlang::inject(
    dplyr::join_by(
      !!track_x_sym == !!track_y_sym,
      !!!dots,
      !!!window_cond,
      !!temporal
    )
  )
  result <- dplyr::left_join(
    x,
    y,
    by = join_spec,
    suffix = suffix,
    multiple = multiple,
    na_matches = na_matches
  )

  if (warn_multiple) {
    warn_multiple_matches(result[[row_x_col]])
  }
  check_reused_y(result[[row_y_col]], on_reused_y)

  result <- result |>
    select(
      -any_of(c(
        window_col,
        row_x_col,
        row_y_col
      ))
    )

  result
}

# For an input set of IDs, count ones that are present 2+ times and warn if
# any are present. Allows us to warn if an `x` record matches more than one `y`
# record in `mt_join_time()`. For nearest-time joins these are usually
# unintended matches (duplicate or equidistant timestamps).
warn_multiple_matches <- function(row_ids) {
  n_multi <- sum(tabulate(row_ids) > 1)

  if (n_multi > 0) {
    cli_warn(
      c(
        "{n_multi} record{?s} in {.arg x} matched multiple `y` records and {?is/are} duplicated in the output.",
        "i" = "Set {.arg multiple} to keep one match per record, or use {.code multiple = \"all\"} to silence this warning."
      ),
      class = "move2_warning_join_multiple_matches"
    )
  }

  invisible(n_multi)
}

# Warn or error if any `y` record was matched to more than one `x` record.
check_reused_y <- function(row_ids, on_reused_y) {
  if (on_reused_y == "ignore") {
    return(invisible(0L))
  }

  n_reused <- sum(tabulate(row_ids) > 1)

  if (n_reused > 0) {
    msg <- "{n_reused} record{?s} in {.arg y} {?was/were} matched to more than one `x` record."

    if (on_reused_y == "error") {
      cli_abort(msg, class = "move2_error_join_reused_y")
    }

    cli_warn(
      c(
        msg,
        "i" = "Use {.code on_reused_y = \"ignore\"} to silence this warning."
      ),
      class = "move2_warning_join_reused_y"
    )
  }

  invisible(n_reused)
}

# move2 supports POSIXct, Date, and numeric timestamp columns, each of which
# implies a different unit for the `window` argument. This validates and ensures
# that the `window` argument is interpreted at the correct time scale.
standardize_window_units <- function(
  window,
  times,
  call = rlang::caller_env()
) {
  if (is.null(window)) {
    return(NULL)
  }

  if (length(window) != 1L || is.na(window)) {
    cli_abort(
      "{.arg window} should be a length-1 non-missing value or {.code NULL}.",
      class = "move2_error_join_window_not_scalar",
      call = call
    )
  }

  if (inherits(window, "difftime")) {
    window <- units::as_units(window)
  }

  # Coerce `window` to the correct time scale based on the move2 timestamp class
  if (is.date(times)) {
    window_unit <- "d"
  } else if (is.time(times)) {
    window_unit <- "s"
  } else {
    window_unit <- NA_character_
  }

  if (is.na(window_unit)) {
    if (inherits(window, "units") || !is.numeric(window)) {
      cli_abort(
        "{.arg window} should be {.cls numeric} when times are {.cls numeric}.",
        class = "move2_error_join_window_type",
        call = call
      )
    }

    window <- as.numeric(window)
  } else {
    if (!inherits(window, "units")) {
      cli_abort(
        "{.arg window} should have units when times are {.cls {class(times)[[1]]}}.",
        class = "move2_error_join_window_type",
        call = call
      )
    }

    window <- as.numeric(units::set_units(
      window,
      window_unit,
      mode = "standard"
    ))
  }

  if (window < 0) {
    cli_abort(
      "{.arg window} should be non-negative.",
      class = "move2_error_join_window_negative",
      call = call
    )
  }

  window
}

# Small wrapper to generate unique, non-conflicting names from an input vector
# `x`, avoiding names in `...` (character vectors or data frames). Only
# (possibly modified) names in `x` are returned. This makes it easier to avoid
# colname clashes when generating names for temporary columns.
get_unique_names <- function(x, ...) {
  avoid <- list(...)
  avoid_chr <- purrr::map(
    avoid,
    ~ {
      if (inherits(.x, "data.frame")) {
        names(.x)
      } else {
        .x
      }
    }
  ) |>
    unlist() |>
    unique()
  make.unique(c(avoid_chr, x)) |> tail(length(x))
}
utils::globalVariables("closest") # for `dplyr::join_by()` in `mt_join_time()`

Try the move2 package in your browser

Any scripts or data that you put into this service are public.

move2 documentation built on Dec. 2, 2026, 1:08 a.m.