我想使用dplyr参数化以下计算,该计算查找Sepal.Length的哪些值与Sepal.Width的多个值相关联:

library(dplyr)

iris %>%
    group_by(Sepal.Length) %>%
    summarise(n.uniq=n_distinct(Sepal.Width)) %>%
    filter(n.uniq > 1)

通常我会这样写:
not.uniq.per.group <- function(data, group.var, uniq.var) {
    iris %>%
        group_by(group.var) %>%
        summarise(n.uniq=n_distinct(uniq.var)) %>%
        filter(n.uniq > 1)
}

但是,此方法会引发错误,因为dplyr使用non-standard evaluation。该函数应如何编写?

最佳答案

您需要使用dplyr函数的标准评估版(只需在函数名称后加上_,即group_by_summarise_),然后将字符串传递给函数,然后将其转换为符号。要参数化summarise_的参数,您将需要使用interp()包中定义的lazyeval。具体来说:

library(dplyr)
library(lazyeval)

not.uniq.per.group <- function(df, grp.var, uniq.var) {
    df %>%
        group_by_(grp.var) %>%
        summarise_( n_uniq=interp(~n_distinct(v), v=as.name(uniq.var)) ) %>%
        filter(n_uniq > 1)
}

not.uniq.per.group(iris, "Sepal.Length", "Sepal.Width")

请注意,在最新版本的dplyr中,dplyr函数的标准评估版为"soft deprecated",以支持非标准评估。

有关使用非标准评估的更多信息,请参见Programming with dplyr vignette

关于r - 将参数传递给dplyr函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27975124/

10-12 17:54
查看更多