使用summarisewith函数时,默认plyr会ddply删除空类别。您可以通过添加来更改此行为.drop = FALSE。summarise但是,这在使用with时不起作用dplyr。还有另一种方法可以在结果中保留空类别吗?
这是一个假数据的例子。
library(dplyr)
df = data.frame(a=rep(1:3,4), b=rep(1:2,6))
# Now add an extra level to df$b that has no corresponding value in df$a
df$b = factor(df$b, levels=1:3)
# Summarise with plyr, keeping categories with a count of zero
plyr::ddply(df, "b", summarise, count_a=length(a), .drop=FALSE)
b count_a
1 1 6
2 2 6
3 3 0
# Now try it with dplyr
df %.%
group_by(b) %.%
summarise(count_a=length(a), .drop=FALSE)
b count_a .drop
1 1 6 FALSE
2 2 6 FALSE
不完全是我所希望的。有没有一种dplyr方法可以达到与中相同的.drop=FALSE结果plyr?