Skip to content

Instantly share code, notes, and snippets.

@brshallo
Created October 20, 2021 23:59
Show Gist options
  • Select an option

  • Save brshallo/9e39f42f4ff84d9c4430b38e993bbde2 to your computer and use it in GitHub Desktop.

Select an option

Save brshallo/9e39f42f4ff84d9c4430b38e993bbde2 to your computer and use it in GitHub Desktop.
Question answered for R4DS mentor hours
library(tidyverse)

tibble(id = c(3:7, NA, NA, 10:12, NA, NA)) %>% 
  mutate(NA_flag = is.na(id),
         NA_ID = cumsum(!NA_flag & lead(NA_flag))) %>% 
  group_by(NA_ID) %>% 
  mutate(NA_count = cumsum(NA_flag) * NA_flag,
         id_new = ifelse(!NA_flag, NA, min(id, na.rm = TRUE) + NA_count),
         id_final = ifelse(NA_flag, id_new, id))
#> # A tibble: 12 x 6
#> # Groups:   NA_ID [3]
#>       id NA_flag NA_ID NA_count id_new id_final
#>    <int> <lgl>   <int>    <int>  <int>    <int>
#>  1     3 FALSE       0        0     NA        3
#>  2     4 FALSE       0        0     NA        4
#>  3     5 FALSE       0        0     NA        5
#>  4     6 FALSE       0        0     NA        6
#>  5     7 FALSE       1        0     NA        7
#>  6    NA TRUE        1        1      8        8
#>  7    NA TRUE        1        2      9        9
#>  8    10 FALSE       1        0     NA       10
#>  9    11 FALSE       1        0     NA       11
#> 10    12 FALSE       2        0     NA       12
#> 11    NA TRUE        2        1     13       13
#> 12    NA TRUE        2        2     14       14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment