lag_group | R Documentation |
Take the lag of a variable for each group. Will check also that there are no missing years.
lag_group(
df,
group_var,
value_var,
time_var,
lagamount = 1,
complete_time = seq(min(df[[time_var]]), max(df[[time_var]]), by = 1L),
default = NA
)
df |
data frame |
group_var |
The grouping variable |
value_var |
The variable to lag over |
time_var |
The time variable. This is necessary as the function makes sure there are no missing years. |
lagamount |
The amount of lag |
complete_time |
Sequence to use for 'completing' df, making sure implicit NAs are turned into explicit ones. |
default |
Default value for missing? NA by default. |
df_test <- data.frame(group = rep(c("a", "b"), each=6),
year = rep(2000:2005, 2),
value = (0:11) ^ 2,
value2 = rnorm(12))
lag_group(df_test, "group", time_var="year", value_var="value", lagamount = -1:2)
## Behaviour with missing years
lag_group(df_test[-4,], "group", time_var="year", value_var="value", lagamount = -1:2)
## Many lags and many variables:
lag_group(df_test[-4,], "group", time_var="year", lagamount = 1:2, value_var = c("value", "value2"))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.