dplyr::mutate unquote RHS

自作多情 提交于 2019-12-11 05:09:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/46992762/dplyrmutate-unquote-rhs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!