类似的问题在here和here,但这些无法解决包括条件或需要在开始时分离零计数并将它们合并回来。
library(data.table)
as.data.table(iris)[Sepal.Length > 6, .(n=.N), .(Species)]
退货
Species n
<fctr> <int>
1: versicolor 20
2: virginica 41
但假设我想包括
setota 0
。
这可以通过使用 dplyr 来实现
iris %>%
group_by(Species, .drop=FALSE) %>%
filter(Sepal.Length > 6) %>%
summarize(n = n())
Species n
<fct> <int>
1 setosa 0
2 versicolor 20
3 virginica 41
在
data.table
中,正确的做法是什么?
谢谢你。
您可以在 [i, j, ] 中进行计算,例如
as.data.table(iris)[, .(n = sum(Sepal.Length > 6)), by = Species]
Species n
<fctr> <int>
1: setosa 0
2: versicolor 20
3: virginica 41