在交叉表中将 NA 设置为“缺失”

问题描述 投票:0回答:1
library(crosstable)
ct1 = crosstable(mtcars2, c(disp, vs), by=am, total="both", 
                 percent_pattern="{n} ({p_row}/{p_col})", percent_digits=0) %>%
    as_flextable()
ct1

如何轻松地将值标签从“NA”更改为“missing”?

r crosstable
1个回答
0
投票

根据我的理解,汇总函数的标签是硬编码在默认汇总函数中的

cross_summary
。但你可以简单地使用复制&。粘贴以编写您自己的摘要函数版本或使用包装函数来设置您所需的标签:

library(crosstable)

cross_summary2 <- function(x, dig = 1, ...) {
  c(
    `Min / Max` = minmax(x, dig = dig, ...),
    `Med [IQR]` = mediqr(x,
      dig = dig, ...
    ), `Mean (std)` = meansd(x,
      dig = dig,
      ...
    ), `N (missing)` = nna(x)
  )
}

cross_summary3 <- function(x, dig = 1, ...) {
  xx <- cross_summary(x, dig = dig, ...)
  names(xx)[names(xx) == "N (NA)"] <- "N (missing)"
  xx
}

crosstable(mtcars2, c(disp, vs),
  by = am, total = "both",
  funs = c(` ` = cross_summary2),
  percent_pattern = "{n} ({p_row}/{p_col})",
  percent_digits = 0
) |> 
  as_flextable()

crosstable(mtcars2, c(disp, vs),
  by = am, total = "both",
  funs = c(` ` = cross_summary3),
  percent_pattern = "{n} ({p_row}/{p_col})",
  percent_digits = 0
) |> 
  as_flextable()

© www.soinside.com 2019 - 2024. All rights reserved.