When you copy the same calculation a third time, make it a function. name <- function(arguments) { body } creates one; the value of the last line is what it returns.
margin_pct <- function(price, cost) {
round((price - cost) / price * 100, 1)
}
margin_pct(50, 30) # 40
An argument can have a default, function(amount, rate = 0.08), used when the caller leaves it out.
Functions you use inside mutate() receive a whole column, so build them from vectorized pieces. if looks at one value and stops with an error on a column; if_else() and case_when() work element by element.
To pass a column name into a dplyr verb inside your function, wrap the argument in double braces: group_by({{ group }}). Without them, dplyr looks for a column literally called group.
A vectorized function, and one that takes a column name.