在我假设的情景中,100个人被问到:你最喜欢的汽车、衬衫和网站的 colored颜色 是什么(红色、蓝色或黄色)?这将生成我的模拟数据框:

colors <- c("red", "blue", "yellow")
set.seed(42)
df <- data.frame(id = 1:100, 
car = sample(colors, 100, replace=TRUE), 
shirt = sample(colors, 100, replace=TRUE), 
website = sample(colors, 100, replace=TRUE)
)

我可以根据gtsum制作一个很好的汇总表:

library(tidyverse)
library(gtsummary)

tbl_summary(df, include = c(car, shirt, website))

enter image description here

我想转置这个表数据,这样结果就有三行(汽车、衬衫和网站)和三列(蓝色、红色和黄色),如下所示:

                # blue  red  yellow 
# Characteristic
car  39 (39%) 40 (40%) 21 (21%)
shirt 39 (39%) 35 (35%) 26 (26%)
website 35 (35%) 32 (32%) 33 (33%)

我try 了一个脚本,它分析一个从:Transpose tbl_summary output开始的连续变量 但结果并不是我想要的.

map(
  c("car", "shirt", "website"),
  ~ tbl_summary(
    df,
    by = all_of(.x),
    include = c(car, shirt, website)
  )
) %>%
  tbl_stack()

enter image description here

有什么建议吗?谢谢.

推荐答案

Bstun包中有一个函数可以执行您所需的操作,它是一个gtsum扩展. https://mskcc-epi-bio.github.io/bstfun/reference/tbl_likert.html

colors <- c("red", "blue", "yellow")
set.seed(42)
df <- data.frame(
  id = 1:100, 
  car = sample(colors, 100, replace=TRUE), 
  shirt = sample(colors, 100, replace=TRUE), 
  website = sample(colors, 100, replace=TRUE)
)

df |> 
  bstfun::tbl_likert(include = c(car, shirt, website)) |> 
  gtsummary::as_kable() # convert to kable to display on SO
Characteristic blue red yellow
car 39 (39%) 40 (40%) 21 (21%)
shirt 39 (39%) 35 (35%) 26 (26%)
website 35 (35%) 32 (32%) 33 (33%)

创建于2023-12-10年第reprex v2.0.2

R相关问答推荐

如何从其他前面列中减go 特定列的平均值?

跨列应用多个摘要函数:summerise_all:列表对象无法强制为double类型'

如何替换R中数据集列中的各种字符串

geom_Ribbon条件填充创建与数据不匹配的形状(ggplot 2 r)

寻找图片边缘

如何 bootstrap glm回归、估计95%置信区间并绘制它?

为什么横向页面会导致officeverse中的页码/节头/页脚出现问题?

我不能在docker中加载sf

在R中无法读入具有Readxl和lApply的数据集

提取第一个下划线和最后一个下划线之间的任何内容,例外情况除外

使用Facet_WRAP时更改框图中线的 colored颜色

找出二叉树中每个 node 在R中的深度?

将一个字符串向量调整为与其他字符串向量完全相同的大小

如果COLSUM为>;0,则COLNAME为向量

提高圣彼得堡模拟的速度

将摘要图添加到facet_WRAP gglot的末尾

删除字符串R中的重复项

在R中添加要打印的垂直线

如何将一列相关性转换为R中的相关性矩阵

使用nls()函数的非线性模型的半正态图