Wrangling data in R, I would like to mutate
a tibble in such a way that the numerical values in the new column are being looked up in a different tibble.
Given a dataset of catheter removals:
# A tibble: 51 x 2
ExplYear RemovalReason
<dbl> <chr>
1 2018 Infection
2 2018 Dysfunction
3 2018 Infection
# ... etc.
where each row corresponds to a single catheter removal, I would like to add a column Implants
that holds the total number of _im_plantations in the year that the catheter was removed (_ex_planted).
The implantation numbers are in a tibble impl_per_year
:
# A tibble: 13 x 2
ImplYear n
<dbl> <int>
1 2006 14
2 2007 46
3 2008 64
# ... etc.
I have tried to mutate
the first tibble with map
and a helper function:
lookup = function(year) { impl_per_year[impl_per_year$ImplYear == year,]$n }
explants %>% mutate(Implants = map(ExplYear, lookup)
But this places lots of empty integer vectors into the Implants
column:
# A tibble: 51 x 3
ExplYear RemovalReason Implants
<dbl> <chr> <list>
1 18 Infection <int [0]>
2 18 Dysfunction <int [0]>
3 18 Infection <int [0]>
# ... etc.
What is the mistake?