0

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%)
DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
  • It is unclear if you want to generate a new table summarizing the percentages for all the conditions, or if you want to add that percentage to each row in the table. Can you post the table itself. You can use triple back-ticks to format as code, and `dput()` to output your data so it can be regenerated in R. – beroe Feb 03 '23 at 00:07
  • I was hoping to add percentages to each row of the table – user21136953 Feb 03 '23 at 00:11

2 Answers2

1

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)

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
  • The answer is similar to [this one](https://stackoverflow.com/questions/67506551/crate-a-table-with-frequencies-and-percents-of-each-row-in-r/67508750#67508750), but with different formatting for the percentage. – DaveArmstrong Feb 03 '23 at 00:46
0
dat<-c("A","A",rep("B",18))
cbind(freq=table(dat), "%" = prop.table(table(dat)) * 100)

  freq  %
A    2 10
B   18 90

user12256545
  • 2,755
  • 4
  • 14
  • 28
  • While this code snippet may be the solution, including a detailed explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Shawn Hemelstrand Feb 03 '23 at 12:57