【问题标题】:Display class of variables in a nice neat table in R-markdown using gt or gtsummary使用 gt 或 gtsummary 在 R-markdown 的漂亮整洁表中显示变量类
【发布时间】:2021-06-06 01:57:53
【问题描述】:

我想很好地显示数据框结构,尤其是显示列名和类。我想做这样的事情:

str(my_df) %>% tbl_summary()

我知道这行不通,但我认为它可以解释我想要做好的事情。表输出中有很多显示类的图像,但我在任何地方都找不到示例代码。我一直在尝试使用 gtsummary。

想要的输出是这样的......

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。到目前为止,您尝试了什么?这些尝试如何不是您想要的。

标签: r r-markdown gtsummary gt


【解决方案1】:

您可以构建您想要显示的数据并使用任何漂亮的表格显示库。

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)

【讨论】:

  • 完美,正是我想要的。
【解决方案2】:

选项 1:

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

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

选项 2:使用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')
        )
    )

选项 3:

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

【讨论】:

    【解决方案3】:

    我们可以使用formattable

    library(dplyr)
    library(tidyr)
    library(formattable)
    iris %>%
         summarise(across(everything(), class)) %>% 
         pivot_longer(cols = everything()) %>%
         formattable::formattable(.)
    

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 2023-04-01
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      相关资源
      最近更新 更多