I am stuck finding the right approach to the following task. My original dataframe has the following structure (with many more gde_nr):
df <- read.table(header = TRUE, text = "
gde_nr month amount
1001 1 4000
1001 3 1002
1001 4 1283
1001 5 4352
1002 3 2
1002 4 34
1002 6 300
")
My goal is to create a full monthly sequence for every gde_nr, like this:
df_result <- read.table(header = TRUE, text = "
gde_nr month amount
1001 1 4000
1001 2 0
1001 3 1002
1001 4 1283
1001 5 4352
1001 6 0
1001 7 0
1001 8 0
1001 9 0
1001 10 0
1001 11 0
1001 12 0
1002 1 0
1002 2 0
1002 3 2
1002 4 34
1002 5 0
1002 6 300
1002 7 0
1002 8 0
1002 9 0
1002 10 0
1002 11 0
1002 12 0
")
In a first step I used group_by followed by nest
library(tidyverse)
df %>%
group_by(gde_nr) %>%
nest()
My ideas to proceede:
A) join a dataframe containing the sequence 1:12 and repeating gde_nr. purrr reduce() might be an option B) use map()
Shure I am open to a competely different approach to this.
Thanks in advance! Jürgen