Search code examples
rr-markdowngtsummarygt

Display class of variables in a nice neat table in R-markdown using gt or gtsummary


I would like to display a dataframe structure nicely, especially showing column names and class. I want to do something kind of like this:

str(my_df) %>% tbl_summary()

I know that doesn't work, but I thought it would explain what I wanted to do well. There are quite a few images showing class in the table output but I can't find example code anywhere. I've been trying with gtsummary.

Desired output something like so...

Desired output


Solution

  • You may construct the data that you want to display and use any of the pretty table display library.

    data <- setNames(stack(sapply(iris, class))[2:1], c('variable', 'class'))
    data
    
    #      variable   class
    #1 Sepal.Length numeric
    #2  Sepal.Width numeric
    #3 Petal.Length numeric
    #4  Petal.Width numeric
    #5      Species  factor
    
    gt::gt(data)
    

    enter image description here