Getting proportion of ranges containing value, by type

Viewed 33

I have a data frame with 3 columns, and 3*m rows, with Lower and Upper representing an interval.

 Lower Upper Type
   x11   y11    1
   x12   y12    1
   ...   ...    .
   x1m   y1m    1
   x21   y21    2
   x22   y22    2
   ...   ...    .
   x2m   y2m    2
   x31   y31    3
   x32   y32    3
   ...   ...    .
   x3m   y3m    3

I want to see what percentage of the Type 1, 2, and 3 intervals contain some value k=3.

I'd like to use the group_by and summarise functions from the tidyverse package but I can't quite get it to work properly.

What I've done so far is:

foo <- my_data_frame %>% group_by(Type) %>% summarise(num_TF = ((Lower<=3)&(Upper>=3)))
foo %>% count(num_TF == TRUE)

and I get a table that looks like:

# A tibble: 6 x 3
# Groups:   Type [3]
   Type `num_TF == TRUE`     n
  <dbl> <lgl>            <int>
1     1 FALSE            17099
2     1 TRUE             82901
3     2 FALSE            10314
4     2 TRUE             89686
5     3 FALSE             5788
6     3 TRUE             94212

However I'm just interested in calculating the proportions of each type and would like to avoid having to manually look at the count and find the proportion from there. Could someone please help me

2 Answers

The mean of a logical vector should be the proportion. So, we could simplify it as

library(dplyr)
my_data_frame %>%
    group_by(Type) %>%
    summarise(num_TF = 100 * mean((Lower <= 3)&( Upper >= 3), na.rm = TRUE))

Here's one way to add the percentages within each group to what you already have.

my_data_frame %>%  
  count(Type, num_TF = ((Lower<=3)&(Upper>=3))) %>%  
  group_by(Type) %>%
  mutate(share = n / sum(n)) %>%
  ungroup()
Related