Đây là một giải pháp và cách tôi đến.
group_by mong đợi điều gì?
> group_by
function (x, ..., add = FALSE)
{
new_groups <- named_dots(...)
Xuống hang thỏ:
> 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))
}
Sử dụng thông tin đó, làm thế nào để đi về việc tạo ra một giải pháp?
# 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
Giải pháp nằm trong trích dẫn các đối số để đánh giá của họ bị trì hoãn cho đến khi họ đang ở trong môi trường bao gồm các 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))
:-) 'tóm tắt [sic]' +1 –
Chỉ cần 'group_by_ (c (" Chick ", v))' thay vì 'group_by (c (" Chick ", v))' .... –
@Ari Nếu bạn sử dụng chính tả của Mỹ, tại sao bạn sử dụng 'tóm tắt' trong mã? –