0

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

Harley
  • 1,305
  • 1
  • 13
  • 28
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. What have you tried so far and how have those attempts not been what you wanted. – MrFlick Jun 06 '21 at 02:53

3 Answers3

3

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Option 1:

library(stringr)
library(tidyverse)
library(DT)

datatable(iris, colnames = str_c(names(iris), ' ', '<', map(iris, class), '>'))

Option 2: Using DT table documentation page

library(stringr)
library(tidyverse)
library(DT)

datatable(iris, colnames = str_c(names(iris), ' ', '<', map(iris, class), '>')) %>% 
    formatStyle('Sepal.Length', fontWeight = styleInterval(5, c('normal', 'bold'))) %>%
    formatStyle(
        'Sepal.Width',
        color = styleInterval(c(3.4, 3.8), c('white', 'blue', 'red')),
        backgroundColor = styleInterval(3.4, c('gray', 'yellow'))
    ) %>%
    formatStyle(
        'Petal.Length',
        background = styleColorBar(iris$Petal.Length, 'steelblue'),
        backgroundSize = '100% 90%',
        backgroundRepeat = 'no-repeat',
        backgroundPosition = 'center'
    ) %>%
    formatStyle(
        'Species',
        transform = 'rotateX(45deg) rotateY(20deg) rotateZ(30deg)',
        backgroundColor = styleEqual(
            unique(iris$Species), c('lightblue', 'lightgreen', 'lightpink')
        )
    )

Option 3:

    datatable(cbind(names(iris), str_c( '<', map(iris, class), '>')), colnames = c('name', 'class')) 
jpdugo17
  • 6,816
  • 2
  • 11
  • 23
1

We could use formattable

library(dplyr)
library(tidyr)
library(formattable)
iris %>%
     summarise(across(everything(), class)) %>% 
     pivot_longer(cols = everything()) %>%
     formattable::formattable(.)
akrun
  • 874,273
  • 37
  • 540
  • 662