R tables with proportion

Viewed 35
ID <- c(1,2,3,4,5,6,7,8)
Hospital <- c("A","A","A","A","B","B","B","B")
risk <- c("Low","Low","High","High","Low","Low","High","High")
retest <- c(1,0,1,1,1,1,0,1)
df <- data.frame(ID, Hospital, risk, retest)
# freq. table
df %>% group_by(risk, Hospital) %>%
  summarise(n=n())%>%
  spread(Hospital,n)

# A tibble: 2 × 3
# Groups:   risk [2]
  risk      A     B
  <chr> <int> <int>
1 High      2     2
2 Low       2     2
#freq. table of retest by risk and Hospital
df %>%
  group_by(risk, Hospital) %>%
  #summarise(n=n()) %>%
  summarise(retestsum = sum(retest))%>%
  spread(Hospital, retestsum)
# A tibble: 2 × 3
# Groups:   risk [2]
  risk      A     B
  <chr> <dbl> <dbl>
1 High      2     1
2 Low       1     2

I want to get the proportions of retest by Hospital and by risk categories. For example, Hospital A, low risk , retested 1 person / 2 person = 50.

enter image description here

Need to create A% B% columns to get the final result of the table below.

enter image description here

Please help me get the prop. columns and also (n=x) part in the final table.

1 Answers

Just divide the second table's numeric values by those of the first. Fortunately elementwise division does not destroy the structure if the two tibbles have the same dimensions:

 d2 <- df1 %>% group_by(risk, Hospital) %>%
     summarise(n=n())%>%
    spread(Hospital,n)
`summarise()` has grouped output by 'risk'. You can override using the `.groups` argument.

 d3 <- df1 %>%
     group_by(risk, Hospital) %>%
     #summarise(n=n()) %>%
     summarise(retestsum = sum(retest))%>%
     spread(Hospital, retestsum)

You can deliver a proportion or a percentage

# proportion
> d3[-1]/d2[-1]
    A   B
1 1.0 0.5
2 0.5 1.0

#percentage
> 100*d3[-1]/d2[-1]
    A   B
1 100  50
2  50 100
``
Related