7

使用 dplyr,我想用一个我可以改变的变量来总结 [原文如此](例如,在循环或应用样式命令中)。

直接输入名称可以正常工作:

library(dplyr)
ChickWeight %>% group_by( Chick, Diet ) %>% summarise( mw = mean( weight ) )

group_by不是为了获取字符向量而编写的,因此传递结果更难。

v <- "Diet"
ChickWeight %>% group_by( c( "Chick", v ) ) %>% summarise( mw = mean( weight ) )
## Error

我将发布一个解决方案,但很想知道其他人是如何解决这个问题的。

4

2 回答 2

11

The underscore functions of dplyr could be useful for that:

ChickWeight %>% group_by_( "Chick", v )  %>% summarise( mw = mean( weight ) )

From the new features in dplyr 0.3:

You can now program with dplyr – every function that uses non-standard evaluation (NSE) also has a standard evaluation (SE) twin that ends in _. For example, the SE version of filter() is called filter_(). The SE version of each function has similar arguments, but they must be explicitly “quoted”.

于 2015-02-08T00:45:56.520 回答
0

这是一个解决方案,以及我是如何做到的。

group_by 期望什么?

> group_by
function (x, ..., add = FALSE) 
{
    new_groups <- named_dots(...)

掉进兔子洞:

> dplyr:::named_dots
function (...) 
{
    auto_name(dots(...))
}
<environment: namespace:dplyr>
> dplyr:::auto_name
function (x) 
{
    names(x) <- auto_names(x)
    x
}
<environment: namespace:dplyr>
> dplyr:::auto_names
function (x) 
{
    nms <- names2(x)
    missing <- nms == ""
    if (all(!missing)) 
        return(nms)
    deparse2 <- function(x) paste(deparse(x, 500L), collapse = "")
    defaults <- vapply(x[missing], deparse2, character(1), USE.NAMES = FALSE)
    nms[missing] <- defaults
    nms
}
<environment: namespace:dplyr>
> dplyr:::names2
function (x) 
{
    names(x) %||% rep("", length(x))
}

使用这些信息,如何着手制定解决方案?

# Naive solution fails:
ChickWeight %>% do.call( group_by, list( Chick, Diet ) ) %>% summarise( mw = mean( weight ) )

# Slightly cleverer:
do.call( group_by, list( x = ChickWeight, Chick, Diet, add = FALSE ) ) %>% summarise( mw = mean( weight ) )
## But still fails with,
## Error in do.call(group_by, list(x = ChickWeight, Chick, Diet, add = FALSE)) : object 'Chick' not found

解决方案在于引用参数,以便它们的评估被延迟,直到它们处于包含xtbl 的环境中:

do.call( group_by, list( x = ChickWeight, quote(Chick), quote(Diet), add = FALSE ) ) %>% summarise( mw = mean( weight ) )
## Bingo!
v <- "Diet"
do.call( group_by, list( x = ChickWeight, quote(Chick), substitute( a, list( a = v ) ), add = FALSE ) ) %>% summarise( mw = mean( weight ) )
于 2015-02-08T00:22:11.720 回答