1

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

jragz
  • 11
  • 1
  • 1
    Possible duplicate of [R: Insert rows for missing dates/times](https://stackoverflow.com/questions/16787038/r-insert-rows-for-missing-dates-times) OR a much better one [computing missing months in timeseries](https://stackoverflow.com/questions/7392637/computing-missing-months-in-timeseries) – Ronak Shah Oct 11 '17 at 05:37
  • I think the problem here is a bit more complex and not fully covered by the methods in the duplicates mentioned. When you look at the data, the gde_nr has to be filled in for every month (1:12). I found out how to add the month numbers and fill in zeros for missing amounts, but not how to add the corresponding entries for gde_nr. – jragz Dec 15 '17 at 17:03

0 Answers0