1

I have a data frame/tibble that includes a factor variable of bins. There are missing bins because the original data did not include an observation in those 5-year ranges. Is there a way to easily complete the series without having to deconstruct the interval?

Here's a sample df.

library(tibble)

df <- structure(list(bin = structure(c(1L, 3L, 5L, 6L, 7L, 8L, 9L, 
10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L), .Label = c("[1940,1945]", 
"(1945,1950]", "(1950,1955]", "(1955,1960]", "(1960,1965]", "(1965,1970]", 
"(1970,1975]", "(1975,1980]", "(1980,1985]", "(1985,1990]", "(1990,1995]", 
"(1995,2000]", "(2000,2005]", "(2005,2010]", "(2010,2015]", "(2015,2020]", 
"(2020,2025]"), class = "factor"), Values = c(2L, 4L, 14L, 11L, 
8L, 26L, 30L, 87L, 107L, 290L, 526L, 299L, 166L, 502L, 8L)), row.names = c(NA, 
-15L), class = c("tbl_df", "tbl", "data.frame"))

df
# A tibble: 15 x 2
   bin         Values
   <fct>        <int>
 1 [1940,1945]      2
 2 (1950,1955]      4
 3 (1960,1965]     14
 4 (1965,1970]     11
 5 (1970,1975]      8
 6 (1975,1980]     26
 7 (1980,1985]     30
 8 (1985,1990]     87
 9 (1990,1995]    107
10 (1995,2000]    290
11 (2000,2005]    526
12 (2005,2010]    299
13 (2010,2015]    166
14 (2015,2020]    502
15 (2020,2025]      8

I would like to add the missing (1945,1950] and (1955,1960] bins.

hmhensen
  • 2,974
  • 3
  • 22
  • 43

2 Answers2

1

bins already has the levels that you want. So you can use complete in your df as :

tidyr::complete(df, bin = levels(bin), fill = list(Values = 0))

# A tibble: 17 x 2
#   bin         Values
#   <chr>        <dbl>
# 1 (1945,1950]      0
# 2 (1950,1955]      4
# 3 (1955,1960]      0
# 4 (1960,1965]     14
# 5 (1965,1970]     11
# 6 (1970,1975]      8
# 7 (1975,1980]     26
# 8 (1980,1985]     30
# 9 (1985,1990]     87
#10 (1990,1995]    107
#11 (1995,2000]    290
#12 (2000,2005]    526
#13 (2005,2010]    299
#14 (2010,2015]    166
#15 (2015,2020]    502
#16 (2020,2025]      8
#17 [1940,1945]      2
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Yes, that's what I added the last part for. `cut_width` has the factor levels that you want, we just need to `complete` it. – Ronak Shah Sep 19 '20 at 03:15
0
df <- orig_df %>% 
    mutate(bin = cut_width(Year, width = 5, center = 2.5)) 

df2 <- df %>% 
    group_by(bin) %>% 
    summarize(Values = n()) %>% 
    ungroup()
tibble(bin = levels(df$bin)) %>% 
    left_join(df2) %>% 
    replace_na(list(Values = 0))
Michael Dewar
  • 2,553
  • 1
  • 6
  • 22