rgtsummaryjanitor

Descriptive table in R with more than one grouping variable


I have a data frame that looks like below.

#Grouping Var1
var1<-sample(c("red",'blue', 'orange'), size=100, replace=T)
var2<-sample(c("US", "Canada", "Europe"), size=100, replace=T)
var3<-rnorm(100)
df<-data.frame(var1, var2, var3)
head(df)

How do I create a table in R that looks roughly like this? I feel like a function in gtsummary or janitor should work, but I cannot figure it out.

Categorical_Variable Mean_var3
var1 empty
red 0.2
blue 0.3
orange 0.1
var2 empty
Canada 0.1
US 0.5
Europe 1

Solution

  • Here is how you can do it with gtsummary.

    library(gtsummary)
    packageVersion("gtsummary")
    #> [1] '1.7.2'
    
    var1<-sample(c("red",'blue', 'orange'), size=100, replace=T)
    var2<-sample(c("US", "Canada", "Europe"), size=100, replace=T)
    var3<-rnorm(100)
    df<-data.frame(var1, var2, var3)
    
    
    tbl_continuous(
      data = df, 
      variable = var3, 
      statistic = ~"{mean}"
    ) |> 
      as_kable()
    
    Characteristic N = 100
    var1
    blue -0.11
    orange 0.01
    red -0.47
    var2
    Canada -0.32
    Europe 0.02
    US -0.23

    Created on 2024-05-02 with reprex v2.1.0