zed <- data.frame(
aAgg = c(5, 10, 15, 20),
bAgg = c(8, 16, 24, 32),
aPg = c(6, 9, 11, 24),
bPg = c(7, 15, 22, 26)
)
diff_func <- function(col) {
return(`{col}Agg` - `{colPg}`)
}
zed %>%
dplyr::mutate(dplyr::across(.cols = c('a', 'b'), .fns = diff_func, .names = "{col}Diff"))
# we want the output that this outputs, without having to have a mutate for each field.
zed <- zed %>%
dplyr::mutate(aDiff = aAgg - aPg) %>%
dplyr::mutate(bDiff = bAgg - bPg)
We are attempting to use dplyr's across
function to create multiple columns. For each column prefix (a
and b
in this scenario), we'd like to compute the difference between prefixAgg
- prefixPg
, and name the new column prefixDiff
. The last 3 lines of code in the example above generate the desired output. Our diff_func
is currently not correct, throwing an error.
Is there a function we can pass to across
that will generate this output?