【问题标题】:How to calculate Standardized Mean Difference for Table1 Package in R?如何计算 R 中 Table1 包的标准化均值差?
【发布时间】:2023-01-09 11:09:21
【问题描述】:

我正在使用包“table1”创建一个精美的表,其中包含额外的列,其中包含我数据集中连续变量的标准化均值差。

SMD 应该是针对表中给定变量分层的治疗组和对照组之间的组合。

我正在努力想出一个好的方法来做这件事,并且希望得到一些帮助来创建计算 SMD 的函数。

这是一些示例代码:

f <- function(x, n, ...) factor(sample(x, n, replace=T, ...), levels=x)
set.seed(427)

n <- 146
dat <- data.frame(id=1:n)
dat$treat <- f(c("Placebo", "Treated"), n, prob=c(1, 2)) # 2:1 randomization
dat$age   <- sample(18:65, n, replace=TRUE)
dat$sex   <- f(c("Female", "Male"), n, prob=c(.6, .4))  # 60% female
dat$wt    <- round(exp(rnorm(n, log(70), 0.23)), 1)

# Add some missing data
dat$wt[sample.int(n, 5)] <- NA

label(dat$age)   <- "Age"
label(dat$sex)   <- "Sex"
label(dat$wt)    <- "Weight"
label(dat$treat) <- "Treatment Group"

units(dat$age)   <- "years"
units(dat$wt)    <- "kg"

my.render.cont <- function(x) {
    with(stats.apply.rounding(stats.default(x), digits=2), c("",
        "Mean (SD)"=sprintf("%s (&plusmn; %s)", MEAN, SD)))
}
my.render.cat <- function(x) {
    c("", sapply(stats.default(x), function(y) with(y,
        sprintf("%d (%0.0f %%)", FREQ, PCT))))
}

    #My attempt at an SMD function
     smd_value <- function(x, ...) {
 x <- x[-length(x)]  # Remove "overall" group
  # Construct vectors of data y, and groups (strata) g
  y <- unlist(x)
  g <- factor(rep(1:length(x), times=sapply(x, length)))
  if (is.numeric(y) & g==1) {
    # For numeric variables, calculate SMD
    smd_val1 <- (mean(y)/sd(y))
  } else if (is.numeric(y) & g==2) {
    # For numeric variables, calculate SMD
    smd_val2 <- (mean(y)/sd(y))
  } else {print("--")
  }
  smd_val <- smdval2 - smdval1
}

table1(~ age + sex + wt | treat, data=dat,  render.continuous=my.render.cont, render.categorical=my.render.cat, extra.col=list(`SMD`=smd_value))

我收到以下错误:

“if (is.numeric(y) & g == 1) { 错误:条件的长度 > 1”

对潜在解决方案的任何见解?

谢谢!

【问题讨论】:

    标签: r function summary smd


    【解决方案1】:

    撞这个!我也在寻找这方面的建议!你想出来了吗?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 2019-12-22
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多