Home > Software engineering >  r cut report results for all intervals, including empty ones
r cut report results for all intervals, including empty ones

Time:05-29

I have some data that I'd like to count occurrences in breaks, such as the following. The runif statement results in a vector with no zeros, so I create two data frames, one with and one without an added zero

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))

The result is

# 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

However, if I don't add the 0 to the data vector I get this.

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

Is there some way to force the second output to include [0,1] 0?

CodePudding user response:

We can use complete afterwards

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))
  • Related