I'm using the data here (specifically the cpi
and grosses
tibbles) and I would like to calculate each of the columns containing dollar amounts (denoted by having 'gross' or 'price' in their names) in terms of their 2020 value. I would then like to order these columns directly after their matches.
The following method was inspired by the post here:
cpi_recent <- cpi %>% # pulls most recent cpi in the tibble
select(cpi) %>%
slice_tail() %>%
pull()
grosses_adj <- grosses %>%
mutate(year_month = floor_date(week_ending, 'month')) %>%
left_join(cpi, 'year_month') %>%
mutate(across(contains(c('gross', 'price')),
list(adj = ~ cpi_recent/cpi * .))) %>% # creates new col in 2020 dollars w/ _adj suffix
select(-year_month, -cpi)
However, this will place all new columns after the last column, by default.
Is there any way to dynamically order the new columns directly after the matching column, like: gross_1, gross_1_adj, price_2, price_2_adj
, etc.? Of course this is trivial using select()
manually, but I'm assuming there is some way to reference these columns dynamically using mutate()
and the .after
argument.