r 剪切所有间隔的报告结果,包括空间隔

r cut report results for all intervals, including empty ones

我有一些数据想计算中断的出现次数,如下所示。 runif 语句产生一个没有零的向量,所以我创建了两个数据帧,一个有零,一个没有零

library(dplyr)
breaks <- c(0, 1, 25, 50, 75, 100)
testValues <-  runif(50, min = 0, max = 100)
testValues_df <- data.frame(lyr1 = testValues)
testValues_w0 <- c(testValues, 0)
testValues_w0_df <- data.frame(lyr1 = testValues_w0)
testValues_df %>% 
  group_by(gr=cut(lyr1, breaks= breaks, include.lowest = FALSE, right = FALSE) ) %>% 
  summarise(n= n()) %>%
  arrange(as.numeric(gr))

testValues_w0_df %>% 
  group_by(gr=cut(lyr1, breaks= breaks, include.lowest = FALSE, right = FALSE) ) %>% 
  summarise(n= n()) %>%
  arrange(as.numeric(gr))

结果是

# A tibble: 5 × 2
gr           n
  <fct>    <int>
1 [0,1)        1
2 [1,25)      12
3 [25,50)     11
4 [50,75)     18
5 [75,100)     9

但是,如果我不将 0 添加到数据向量中,我会得到这个。

 A tibble: 4 × 2
  gr           n
  <fct>    <int>
1 [1,25)      12
2 [25,50)     11
3 [50,75)     18
4 [75,100)     9

有没有办法强制第二个输出包含 [0,1] 0?

之后我们可以使用complete

library(dplyr)
library(tidyr)
testValues_w0_df %>% 
  group_by(gr=cut(lyr1, breaks= breaks, include.lowest = FALSE, 
      right = FALSE) ) %>% 
  summarise(n= n(), .groups = 'drop') %>%
  arrange(as.numeric(gr)) %>% 
  complete(gr = levels(gr), fill = list(n = 0))