给定一个引用列 z
,我想用dplyr
将每一列转换为:
x = log(x) - log(z)
我要 z
是一个字符串,或者更好的是,一个带引号的表达式(例如,由用户输入 - 所有这些都在一个函数中)。这是我尝试过的:
library(dplyr)
m <- data.frame(x=1:5,y=11:15,z=21:25)
denom = "z"
这有效:m %>%
mutate(across(x:z ,
list(~ log(.) - log(z) )))
这失败了: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.
这也失败了: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)))))
最佳答案
您也可以使用 get()
:
m %>% mutate(across(.fns = list(~ log(.) - log(get(denom)))))
关于从 dplyr 中的变量中引用列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68349087/