这是一个解决方案,以及我是如何做到的。
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
解决方案在于引用参数,以便它们的评估被延迟,直到它们处于包含x
tbl 的环境中:
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 ) )