Home > Mobile >  How can I percentage makeup of TRUE from a vector?
How can I percentage makeup of TRUE from a vector?

Time:12-13

This is the code used to derive the first table in my question.

JH %>% group_by(ATT_ID, CAR=="B") %>%
summarize(count = n(), .groups = "drop")
ATT_ID CAR == "B" Count
ONE FALSE 1
TWO TRUE 1
THREE TRUE 3
THREE FALSE 5
FOUR FALSE 2
FIVE TRUE 4
SIX TRUE 8
SIX FALSE 4

How can I get the table above to look like:

ATT_ID Percentage of "B"
ONE 0%
TWO 100%
THREE 37.5%
FOUR 0%
FIVE 100%
SIX 67%
  • Notice how some ID's are seen twice so as to show the presence of both FALSE & TRUE whereas other ID's appear once to showcase the presence of only one or the other.

Thank you

CodePudding user response:

You can do the following:

dt %>% 
  group_by(ATT_ID) %>%
  summarize(`Percentage of "B"` = sprintf("%2.0f%%",100*mean(`CAR =="B"`)))

Output:

# A tibble: 4 × 2
  ATT_ID `Percentage of "B"`
  <chr>  <chr>              
1 FOUR   "100%"             
2 ONE    "67%"              
3 THREE  " 0%"              
4 TWO    "50%"              

CodePudding user response:

We may do

library(dplyr)
df1 %>%
   group_by(ATT_ID) %>%
   summarise(`Percentage of "B"` = paste0(round(mean(`CAR == "B"`) * 100)), "%"))
  • Related