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)
我们尝试使用dplyr的
across
函数创建多列。对于每个列前缀(在此场景中为a
和b
),我们想要计算prefixAgg
- prefixPg
的差值,并将新列命名为prefixDiff
。上面代码示例中的最后3行生成了期望的输出结果。我们当前的diff_func
不正确,会导致错误。
有没有一个可以传递给across
的函数来生成这个输出呢?