这是this个问题的后续问题

请考虑以下示例:

library(gtsummary)
library(gtreg)
library(dplyr)
library(tidyr)

df <- structure(
  list(id = c("patient1", "patient2", "patient3", "patient4", 
              "patient5"), x = c("h,a,a", "i", "i", "i,a,e", "h")), 
  class = "data.frame", row.names = c(NA, -5L)
)

df1 <- structure(
  list(id = c("patient1", "patient2", "patient3", "patient4", 
              "patient5"), y = c("yes", "no", "yes", "yes", "no")), 
  class = "data.frame", row.names = c(NA, -5L)
)



# prep data for a table
tbl <- df |> 
  separate_rows(x, sep = ",") |> 
  select(x) |>
  count(x) |> 
  mutate(percent = round(n/nrow(df)*100)) |> 
  mutate(N_percent = paste0(n,"/", nrow(df), " (",percent,"%)"), .keep = "unused") |> 
  select(x, N = N_percent) |> 
  mutate(grouping_var = "x", .before = 1L) |> 
  # create a gtsummary class listing
  tbl_listing(df, group_by = grouping_var) |> 
  # style table with gtusmmary functions to make it look like `tbl_summary()`
  modify_header(
    x ~ "**Characteristic**",
    N ~ "**N = 5**"
  ) |> 
  modify_column_alignment(N, align = "center") |> 
  modify_footnote(N = "n/N (%)")


tbl1 <- df1 |> 
  select(y) |> 
  tbl_summary(
    type = list(y ~ "categorical"))


tbl_stack(
  tbls = list(tbl, tbl1)
  )

结果是移动了第二个表:

enter image description here

我预计会是这样的:

enter image description here

推荐答案

在我的answer的基础上,你的上一个问题,这里是另一个 Select ,以达到你想要的结果使用tbl_custom_summary.这里使用的是我的定制函数的一个通用版本,它还允许传递标识符列的名称,并通过添加distinct参数允许处理这两种类型的变量.

library(dplyr, warn = FALSE)
library(tidyr)
library(gtsummary)

df <- df |>
  left_join(df1, by = "id")

my_summary <- function(variable, .id = "id", distinct = FALSE) {
  function(data, full_data, stat_display, ...) {
    if (distinct) {
      data <- distinct(data, .data[[.id]], .data[[variable]])
    }
    data |>
      summarise(
        n = n(),
        N = n_distinct(full_data[[.id]]),
        p = n / N
      )
  }
}

tbl <- df %>%
  separate_rows(x, sep = ",") |>
  tbl_custom_summary(
    include = -id,
    stat_fns = list(
      ~ my_summary("x", "id"),
      ~ my_summary("y", "id", distinct = TRUE)
    ),
    type = everything() ~ "categorical",
    statistic = list(
      x ~ "{n}/{N} ({p}%)",
      y ~ "{n} ({p}%)"
    )
  )

tbl |>
  modify_header(
    stat_0 ~ paste0("**N = ", nrow(df), "**")
  ) |> 
  modify_footnote(stat_0 = "n/N (%)")

enter image description here

R相关问答推荐

使用geom_rect的带有事件注释的时间序列图

用apply/map/etch替换循环以加快速度

R:随机抽取所有可能排列的样本

将R data.frame转换为json数组(源代码)

卸载安装了BRM的模型发出的警告

使用ggplot将平滑线添加到条形图

带有gplot 2的十字舱口

使用case_match()和char数组重新编码值

如何将旋转后的NetCDF转换回正常的纬度/经度网格,并使用R?

如何在ggplot中标记qqplot上的点?

如何在R中描绘#符号?

如何在R forestplot中为多条垂直线分配唯一的 colored颜色 ?

在ggplot2的框图中绘制所有级别的系数

KM估计的差异:SvyKm与带权重的调查

随机森林的带Shap值的蜂群图

如何将一个方阵分解成没有循环的立方体

根据r中另一个文本列中给定的范围对各列求和

为R中的16组参数生成10000个样本的有效方法是什么?

避免在图例中显示VLINS组

R仅当存在列时才发生变异