Reputation: 4586
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()
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.
Upvotes: 1
Views: 884
Reputation: 11898
Your code should work as you expect by changing the line where you define qcol
to:
qcol <- as.symbol(sprintf('q%i', i))
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
.
Upvotes: 3