R 中摘要 table 的呈现样式

Presentation style of the summary table in R

我正在尝试在 R 中创建摘要 table,就像下面 Table 4 中的那样。

现在我所拥有的是下面这样的东西。我不确定如何在 R 中自动生成 Latex 代码来创建一个像上面那样的 table。

我正在使用以下 R 代码生成 table。然后我将代码复制并粘贴到 Latex 中以使其显示在 pdf 中。

#Build a rough summary table
summary1 <-
  list("Age (Years)" =
         list("Missing"  = ~ sum(is.na(df$age_years)),
              "Type" = ~ if(is.numeric(df$age_years)==TRUE) {print("Numeric")} else {print("Character")},
              "Min"       = ~ min(age_years),
              "Max"       = ~ max(age_years),
              "Mean" = ~ format(round(mean(df$age_years), 2), nsmall = 2),
              "SD" = ~ format(round(sd(df$age_years), 2), nsmall = 2)),
       "Female" =
         list("Missing"  = ~ sum(is.na(df$sex_DV)),
              "Type" = ~ if(is.numeric(df$sex_DV)==TRUE) {print("Numeric")} else {print("Character")},
              "Min"       = ~ min(sex_DV),
              "Max"       = ~ max(sex_DV),
              "Mean" = ~ format(round(mean(df$sex_DV), 2), nsmall = 2),
              "SD" = ~ format(round(sd(df$sex_DV), 2), nsmall = 2))
       )

whole <- summary_table(df,summary1)
whole

欢迎任何帮助。谢谢!

编辑: 具有可重现的部分数据(不是实际数据)

> df
      age_years       sex
    1          33          0
    2          11          1
    3          45          1
    4          67          0
    5          8           0
    6          99          0

根据提供的示例数据,您可以实现以下目标。

df <- data.frame(
   age_years = c(33L, 11L, 45L, 67L, 8L, 99L),
         sex = c(0L, 1L, 1L, 0L, 0L, 0L)
)

names <- names(df)
missing_counts <- sapply(df, function(x) sum(is.na(x)))
classes <- sapply(df, function(x) class(x))
min <- sapply(df, function(x) min(x, na.rm = TRUE))
max <- sapply(df, function(x) max(x, na.rm = TRUE))
sd <- sapply(df, function(x) sd(x, na.rm = TRUE))
mean <- sapply(df, function(x) mean(x, na.rm = TRUE))

knitr::kable(as.data.frame(cbind(names, missing_counts, classes, min, max, mean, sd), row.names = FALSE))
names missing_counts classes min max sd mean
age_years 0 integer 8 99 34.8161839762296 43.8333333333333
sex 0 integer 0 1 0.516397779494322 0.333333333333333

旁注,性别编码为 0 和 1,您可能希望此数据是一个因素而不是数字,并且您可能不想报告此统计信息的 mean/SD。