| sum_fill | R Documentation |
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.
sum_fill(df, var, change_var, start_with_zero = TRUE, .by = NULL)
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). |
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.
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")
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.