iv_diff {ivs}R Documentation

Diff a vector to create an interval vector

Description

iv_diff() is a convenient way to generate an iv from a preexisting vector, as long as that vector is in strictly increasing order. It returns an iv that is 1 element shorter than x (unless x is already empty).

It is particularly useful for creating an iv column from an existing column inside of dplyr::mutate(), but requires you to explicitly handle padding in that case, see the examples.

Missing values are allowed, and will be propagated to each side of the resulting interval after applying the diff.

Usage

iv_diff(x)

Arguments

x

⁠[vector]⁠

A vector in strictly increasing order.

Details

iv_diff() is inspired by diff().

Value

An iv using x as the inner type, with size equal to max(0L, vec_size(x) - 1L).

Examples

x <- as.Date("2019-01-01") + c(0, 5, 7, 10, 19)
x

# Notice how the boundaries don't overlap, because the closing `)` aligns
# with an opening `[`.
iv_diff(x)

# Like `iv()`, missing values propagate to both boundaries of the interval.
# Before missing value propagation was applied, it looked like this:
# [1, NA), [NA, 2), [2, 3)
x <- c(1, NA, 2, 3)
iv_diff(x)

# Values in `x` must be in strictly increasing order to generate a valid
# interval vector
x <- c(1, 0, 2, 2)
try(iv_diff(x))

x <- c(1, NA, 0)
try(iv_diff(x))

# ---------------------------------------------------------------------------
# Use with `mutate()`

library(dplyr)

# `iv_diff()` is useful for converting a pre-existing column into an interval
# vector, but you'll need to apply padding to ensure that the size of the
# diff-ed result is the same as the number of rows in your data frame. There
# are two main ways to pad, which are explored below.
df <- tibble(x = c(1, 3, 6))

# Pad with a known lower/upper bound
df %>% mutate(iv = iv_diff(c(0, x)))
df %>% mutate(iv = iv_diff(c(x, Inf)))

# Pad with a missing value, which results in a fully missing interval
df %>% mutate(iv = iv_diff(c(NA, x)))
df %>% mutate(iv = iv_diff(c(x, NA)))

[Package ivs version 0.2.0 Index]