1

Original Data

id hhcode value
 1      1   4.1
 1      2   4.5
 1      3   3.3
10      5   3.2

Required Output

id hhcode value
1      1   4.1
1      2   4.5
1      3   3.3
1      5    0  
10     1    0  
10     2    0  
10     3    0  
10     5   3.2

What got so far

df <- data.frame(
 id      = c(1, 1, 1, 10),
  hhcode  = c(1, 2, 3, 5),
  value   = c(4.1, 4.5, 3.3, 3.2)
)

library(statar)
library(tidyverse)
df %>% 
  group_by(id) %>% 
  fill_gap(hhcode, full = TRUE)

# A tibble: 10 x 3
# Groups:   id [2]
      id hhcode value
   <dbl>  <dbl> <dbl>
 1     1      1   4.1
 2     1      2   4.5
 3     1      3   3.3
 4     1      4  NA  
 5     1      5  NA  
 6    10      1  NA  
 7    10      2  NA  
 8    10      3  NA  
 9    10      4  NA  
10    10      5   3.2

Any hint to get the required output?

Sotos
  • 51,121
  • 6
  • 32
  • 66
MYaseen208
  • 22,666
  • 37
  • 165
  • 309

1 Answers1

3

We could use complete

library(tidyverse)
complete(df, id, hhcode, fill = list(value = 0))
# A tibble: 8 x 3
#     id hhcode value
#  <dbl>  <dbl> <dbl>
#1     1      1   4.1
#2     1      2   4.5
#3     1      3   3.3
#4     1      5   0  
#5    10      1   0  
#6    10      2   0  
#7    10      3   0  
#8    10      5   3.2
akrun
  • 874,273
  • 37
  • 540
  • 662