library(airPb)
library(dplyr)
library(tidyr)
library(purrr)

Example 2: Using the add_scaled_airPb() wrapper function to automatically apply scaling factors to air lead estimates.

A common use case is calculating monthly exposures. For example, we may have a pair of coordinates recorded annually for each participant. In the data below, we have 2 unique ids, with lat/lon recorded once per year.

We want to scale the air lead measurements to monthly exposures between these dates, but we need start_date and end_date columns that represent the monthy time periods we want to average over.

d <- d %>% 
  mutate(from = date,
         to = from + lubridate::years(1)) %>% 
  group_by(id, date) %>% 
  nest() %>% 
  mutate(dates = map(data, ~seq.Date(from = .x$from, 
                                     to = .x$to, 
                                     by = '3 months'))) %>% 
  unnest(cols=c('data', 'dates')) %>% 
  dplyr::select(-from, -to) %>% 
  rename(start_date = dates) %>% 
  mutate(end_date = lead(start_date)) %>% 
  filter(!is.na(end_date)) %>% 
  ungroup()

d %>% 
  mutate(scaled_airPb = add_scaled_airPb(.))
#> # A tibble: 20 x 7
#>        id date         lon   lat start_date end_date   scaled_airPb
#>     <int> <date>     <dbl> <dbl> <date>     <date>            <dbl>
#>  1 809089 2010-01-08 -84.7  39.2 2010-01-08 2010-04-08        0.549
#>  2 809089 2010-01-08 -84.7  39.2 2010-04-08 2010-07-08        0.535
#>  3 809089 2010-01-08 -84.7  39.2 2010-07-08 2010-10-08        1.07 
#>  4 809089 2010-01-08 -84.7  39.2 2010-10-08 2011-01-08        0.765
#>  5 809089 2011-01-08 -84.7  39.2 2011-01-08 2011-04-08        0.380
#>  6 809089 2011-01-08 -84.7  39.2 2011-04-08 2011-07-08        0.495
#>  7 809089 2011-01-08 -84.7  39.2 2011-07-08 2011-10-08        0.612
#>  8 809089 2011-01-08 -84.7  39.2 2011-10-08 2012-01-08        0.441
#>  9 809089 2012-01-08 -84.7  39.2 2012-01-08 2012-04-08        0.538
#> 10 809089 2012-01-08 -84.7  39.2 2012-04-08 2012-07-08        0.389
#> 11 809089 2012-01-08 -84.7  39.2 2012-07-08 2012-10-08        0.263
#> 12 809089 2012-01-08 -84.7  39.2 2012-10-08 2013-01-08        0.567
#> 13 799697 2011-01-10 -84.4  39.2 2011-01-10 2011-04-10        0.292
#> 14 799697 2011-01-10 -84.4  39.2 2011-04-10 2011-07-10        0.405
#> 15 799697 2011-01-10 -84.4  39.2 2011-07-10 2011-10-10        0.536
#> 16 799697 2011-01-10 -84.4  39.2 2011-10-10 2012-01-10        0.317
#> 17 799697 2012-02-10 -84.4  39.2 2012-02-10 2012-05-10        0.361
#> 18 799697 2012-02-10 -84.4  39.2 2012-05-10 2012-08-10        0.178
#> 19 799697 2012-02-10 -84.4  39.2 2012-08-10 2012-11-10        0.260
#> 20 799697 2012-02-10 -84.4  39.2 2012-11-10 2013-02-10        0.691