Learn R Programming

whep (version 0.2.0)

sum_fill: Fill gaps summing the previous value of a variable to the value of another variable.

Description

Fills gaps in a variable with the sum of its previous value and the value of another variable. When a gap has multiple observations, the values are accumulated along the series. When there is a gap at the start of the series, it can either remain unfilled or assume an invisible 0 value before the first observation and start filling with cumulative sum.

Usage

sum_fill(df, var, change_var, start_with_zero = TRUE, .by = NULL)

Value

A tibble dataframe (ungrouped) where gaps in var have been filled, and a new "source" variable has been created indicating if the value is original or, in case it has been estimated, the gapfilling method that has been used.

Arguments

df

A tibble data frame containing one observation per row.

var

The variable of df containing gaps to be filled.

change_var

The variable whose values will be used to fill the gaps.

start_with_zero

Logical. If TRUE, assumes an invisible 0 value before the first observation and fills with cumulative sum starting from the first change_var value. If FALSE (default), starting NA values remain unfilled.

.by

A character vector with the grouping variables (optional).

Examples

Run this code
sample_tibble <- tibble::tibble(
  category = c("a", "a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "b"),
  year = c(
    "2015", "2016", "2017", "2018", "2019", "2020",
    "2015", "2016", "2017", "2018", "2019", "2020"
  ),
  value = c(NA, 3, NA, NA, 0, NA, 1, NA, NA, NA, 5, NA),
  change_variable = c(1, 2, 3, 4, 1, 1, 0, 0, 0, 0, 0, 1)
)
sum_fill(
  sample_tibble,
  value,
  change_variable,
  start_with_zero = FALSE,
  .by = c("category")
)
sum_fill(
  sample_tibble,
  value,
  change_variable,
  start_with_zero = TRUE,
  .by = c("category")
)

Run the code above in your browser using DataLab