Given a reference column z
, I want to use dplyr
to transform each column as:
x = log(x) - log(z)
I want z
to be a string, or even better, a quoted expression (e.g. input by a user - all of this is within a function).
Here is what I've tried:
library(dplyr)
m <- data.frame(x=1:5,y=11:15,z=21:25)
denom = "z"
This works:
m %>%
mutate(across(x:z ,
list(~ log(.) - log(z) )))
This fails:
m %>%
mutate(across(x:z ,
list(~ log(.) - log(rlang::sym(denom)))))
# Error: Problem with `mutate()` input `..1`.
# ℹ `..1 = across(x:z, list(~log(.) - log(rlang::sym(denom))))`.
# ✖ non-numeric argument to mathematical function
# Run `rlang::last_error()` to see where the error occurred.
This also fails:
m %>%
mutate(across(x:z ,
list(~ log(.) - log(!!denom) )))
# Error: Problem with `mutate()` input `..1`.
# ℹ `..1 = across(x:z, list(~log(.) - log("z")))`.
# ✖ non-numeric argument to mathematical function
# Run `rlang::last_error()` to see where the error occurred.
# > #list(~ log(.) - log(rlang::sym(denom)))))