在 data.table 的 .N 中进行条件计数时,保持行数为零

问题描述 投票:0回答:1

类似的问题在herehere,但这些无法解决包括条件或需要在开始时分离零计数并将它们合并回来。

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
中,正确的做法是什么?

谢谢你。

r data.table
1个回答
0
投票

您可以在 [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
© www.soinside.com 2019 - 2024. All rights reserved.