Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

r cut report results for all intervals, including empty ones

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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?

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading