dplyr :: mutate取消引用RHS [英] dplyr::mutate unquote RHS
问题描述
我想知道如何正确地UQ
在dplyr
方法(如mutate
)中在RHS上字符串创建变量名.在此MWE的wilcox.test
部分中查看我在注释中得到的错误消息:
I am wondering how to properly UQ
string created variable names on the RHS in dplyr
methods like mutate
. See the error messages I got in comments in the wilcox.test
part of this MWE:
require(dplyr)
dfMain <- data.frame(
base = c(rep('A', 5), rep('B', 5)),
id = letters[1:10],
q0 = rnorm(10)
)
backgs <- list(
A = rnorm(13),
B = rnorm(11)
)
fun <- function(dfMain, i = 0){
pcol <- sprintf('p%i', i)
qcol <- sprintf('q%i', i)
(
dfMain %>%
group_by(id) %>%
mutate(
!!pcol := ifelse(
!is.nan(!!qcol) &
length(backgs[[base]]),
wilcox.test(
# !!(qcol) - backgs[[base]]
# object 'base' not found
# (!!qcol) - backgs[[base]]
# non-numeric argument to binary operator
(!!qcol) - backgs[[base]]
)$p.value,
NaN
)
)
)
}
dfMain <- dfMain %>% fun()
我猜在!!(qcol) ...
上它被解释为我想取消整个表达式的引用,不仅是变量名,这就是为什么它找不到base
的原因?我还发现(!!qcol)
返回字符串本身,因此-
运算符无法处理它也就不足为奇了.
I guess at !!(qcol) ...
it is interpreted as I would like to unquote the whole expression not only the variable name that's why it does not find base
? I also found out that (!!qcol)
returns the string itself so no surprise the -
operator is unable to handle it.
推荐答案
通过将定义qcol
的行更改为:
Your code should work as you expect by changing the line where you define qcol
to:
qcol <- as.symbol(sprintf('q%i', i))
也就是说,由于qcol
是字符串,因此您需要先将其转换为符号,然后才能取消引用,以便在mutate
中对其进行正确的评估.另外,我假设您要引用的列是您在数据中定义的q0
列,而不是不存在的名为qval0
的列.
That is, since qcol
was a string, you needed to turn it into a symbol before unquoting for it to be evaluated correctly in your mutate
. Also I presume the column you wanted to refer to was the q0
column you defined in your data, not a non-existent column named qval0
.
这篇关于dplyr :: mutate取消引用RHS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!