I'm using mutate_if
to modify columns of some dataframes in my workspace. When using only mutate
I can create variables based on pre-created ones, e.g.
x %>%
mutate(new = column_a * 2,
new_2 = new * 2)
But this approach doesn't work with mutate_if
so I have to make some kind of 'recursive method' creating each variable from the 'beginning' e.g.
mutate_if(!str_detect(names(.), 'date|PIB|Deflator|[$]'),
.funs = list(Real = ~ . / Deflator,
Real_YoY = ~ (((. / Deflator) / lag((. / Deflator), 12))-1) * 100))
Which the desired output is like:
mutate_if(!str_detect(names(.), 'date|PIB|Deflator|[$]'),
.funs = list(Real = ~ . / Deflator,
Real_YoY = ~ ((Real / lag(Real, 12))-1) * 100))
Is there some way to organize the code to get close this? Thank you!
Reproducible example:
x <- data.frame(x = seq(1,10),
x1 = seq(21,30),
y = seq(10,19))
x %>% mutate_if(str_detect(colnames(.), 'x'),
.funs = list(new = ~ (. * 2),
new2 = ~ (. * 2) * 4)) # where (. * 2) could make reference to the variable 'new'