在 R table1 包中使用自定义函数

问题描述

我正在尝试使用 table1 包在 R 中构建数据汇总表。有谁知道是否可以指定要呈现的自定义函数而不是 stats.default 函数?我想使用 Envstats 包中的 geoSD 和 geoMean 函数。有什么想法吗?

解决方法

您可以传入您自己的自定义渲染函数。该函数应生成一个命名字符向量,其中第一个元素的名称将替换为变量的名称。如果您希望避免这种行为,请将第一个元素设为空字符串。

library(table1)

render.continuous.custom <- function(x,...) {
  attr(x,"label") <- NULL # strip labels because geo.+() will choke if present
  c(
    "","geoMean" = format(round(EnvStats::geoMean(x),3),nsmall = 3),"geoSD"   = format(round(EnvStats::geoSD(x),nsmall = 3)
  )
}

table1(~ mpg | factor(cyl),mtcars,render.continuous = render.continuous.custom)

enter image description here