使用tidyr :: complete with group_by [英] Using tidyr::complete with group_by
本文介绍了使用tidyr :: complete with group_by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有人知道 tidyr :: complete()
是否支持通过 group_by()
进行分组?
Does anyone know if tidyr::complete()
supports grouping via group_by()
?
确切地说:我有一些数据框看起来像这样
To be precise: I have some data frame that looks like this
df <- data.frame(
"ID" = rep(1:2, each = 2),
"Col1" = c("A", NA, "AA", NA),
"Col2" = c("B", "C", "BB", "CC"))
现在我想使用 complete()
和 group_by()
来计算所有可能的组合每个组!
Now i'd like to use complete()
and group_by()
to compute all possible combinations per group!
df %>%
group_by(ID) %>%
complete(Col1, Col2)
Error in .Call("dplyr_left_join_impl", PACKAGE = "dplyr", x, y, by_x, :
negative length vectors are not allowed
这会导致错误,但是,使用 complete()
而不进行分组,我想要的。
This causes an error. However, using complete()
without grouping works but thats not what i want.
df %>%
complete(Col1, Col2)
问题:
- / code>完成()根本不适用于
group_by
? - 如果是这样,我该怎么做(最好不用循环)?
- Have I done anything wrong, or does
complete()
simply not work withgroup_by
? - If so, how could I do this instead (preferably without using a loop)?
推荐答案
您可以使用完成
和 group_by
,但您必须使用 do
语句:
You could do it using complete
and group_by
, but you have to use a do
statement:
df %>%
group_by(ID) %>%
do(complete(., Col1, Col2, fill = list(ID = .$ID)))
这篇关于使用tidyr :: complete with group_by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文