## Recordering visits

  var_list_order <- unique(data_intermediate$visit) %>%
    sort() %>%
    as.character()


## Creating table of frequencies
count_ns <- tabyl(data_intermediate, value, visit, show_missing_levels = FALSE) %>%
  relocate(value, var_list_order) %>%
  untabyl() %>%
  adorn_totals(where = 'row') %>%
  mutate(across(.fns = ~ format(.x, big.mark = ',')))


## Adding percentages and formatting
table_output <- tabyl(data_intermediate, value, visit, show_missing_levels = FALSE) %>%
  relocate(value, var_list_order) %>%
  untabyl() %>%
  adorn_percentages(denominator = 'col') %>%
  adorn_totals(where = 'row') %>%
  adorn_pct_formatting(digits = 1) %>%
  adorn_ns(ns = count_ns, position = 'front')


## Renaming columns
names(table_output)[-1] <- paste0('Visit ',names(table_output)[-1])

## Print table
table_output %>%
  kable() %>%
  kable_styling() %>%
  row_spec(row = nrow(table_output), bold = TRUE)


 cat('\n')
 cat('\n')


  ## Plot of percentages

 # Determine if manual color scale can be used

 if(length(unique(data_intermediate$value)) > length(combined_color_palette))
 {

   # Doesn't use our manual color scale, uses R's default colors
   # Removes legend. (takes up too much space with a ton of values)

  data_intermediate %>%
    group_by(visit, value) %>%
    count() %>%
    ggplot(aes(y = n, x = factor(visit), fill = factor(value))) + 
    geom_bar(stat = 'identity', position = 'fill') +
    theme_bw() +
    labs(
      title = paste0('Percentage of ', current_cat),
      subtitle = current_cohort,
      fill = element_blank()) +
     theme(legend.position = 'none') +
    scale_y_continuous(labels = scales::percent_format()) +
    xlab('Visit') +
    ylab('Percentage')  

 } else 
 {

  data_intermediate %>%
    group_by(visit, value) %>%
    count() %>%
    ggplot(aes(y = n, x = factor(visit), fill = factor(value))) + 
    geom_bar(stat = 'identity', position = 'fill') +
    theme_bw() +
    labs(
      title = paste0('Percentage of ', current_cat),
      subtitle = current_cohort,
      fill = element_blank()) +
    scale_fill_manual(values = combined_color_palette) + ## Color palette that accommodates more values
    scale_y_continuous(labels = scales::percent_format()) +
    xlab('Visit') +
    ylab('Percentage')  

 }


Try the psHarmonize package in your browser

Any scripts or data that you put into this service are public.

psHarmonize documentation built on April 4, 2025, 1:50 a.m.