Home > database >  How to add frequency % to tables
How to add frequency % to tables

Time:02-03

I am working on making a baseline characteristic table for a study and I am wondering if there is a way to show the percent of patients in which a baseline demographic occurs? I can make a table and then calculate in r as a separate code but there has to be a way to automate it so that the percentage of the total shows up when I run the code (ex: 2/20 patients have diabetes at baseline - I want to display that the value is 10%).

Thanks in advance for your help!

table(v1, v2)

#See result of table and then do the math in R

2/20

My ideal table would look like this:

           diabetes y       diabetes n
drug x        1 (10%)          9 (90%)

CodePudding user response:

How about this:

library(janitor)
library(dplyr)

drug <- sample(c("a", "b", "c"), 100, replace=TRUE)
diabetes = sample(c("y", "n"), 100, replace=TRUE)
dat <- data.frame(drug = drug, diabetes = diabetes)
dat %>%
  tabyl(drug, diabetes) %>%
  adorn_percentages("row") %>% 
  adorn_pct_formatting(digits=0) %>% 
  adorn_ns(position = "front")
#>  drug        n        y
#>     a 21 (51%) 20 (49%)
#>     b 11 (44%) 14 (56%)
#>     c 19 (56%) 15 (44%)

Created on 2023-02-02 by the reprex package (v2.0.1)

CodePudding user response:

dat<-c("A","A",rep("B",18))
cbind(freq=table(dat), "%" = prop.table(table(dat)) * 100)

  freq  %
A    2 10
B   18 90

  • Related