Here's one solution and how I arrived at it.
What does group_by expect?
> group_by
function (x, ..., add = FALSE)
{
new_groups <- named_dots(...)
Down the rabbit hole:
> 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))
}
Using that information, how to go about crafting a solution?
# 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
The solution lies in quoting the arguments so their evaluation is delayed until they're in the environment that includes the 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 ) )
summarize [sic]
+1 – Acceptantgroup_by_( c( "Chick", v ) )
instead ofgroup_by( c( "Chick", v ) )
.... – Pifflesummarise
in code? – Porettdplyr
, you could also just do it easily withdata.table
:) as inlibrary(data.table) ; as.data.table(ChickWeight)[, .(mw = mean(weight)), c("Chick", v)]
– Pifflesummarise
as well, mainly because there is nosummarize_each
. One less thing I have to remember. – Higinbothamsummarize_each
is probably an oversight). – Porettsummarize_each
alias. – Blameless