You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用modelsummary的datasummary合并因子与数值变量到同一表格问题

问题核心原因

你的代码中存在一处冗余赋值错误:在定义完class和region两个因子变量后,你又添加了两行代码将这两列的所有值统一覆盖为0:

tmp$class <- 0
tmp$region <- 0

这导致class和region两列的取值完全一致,N_alt函数的第二个判断条件永远不会被触发,region变量的统计结果自然会和class变量完全相同。

修复方案

  1. 首先删除上述两行冗余的赋值代码
  2. 调整N_alt函数的判断逻辑,取向量第一个值匹配即可,避免全向量匹配的歧义
  3. 不需要尝试直接传入向量作为统计量,datasummary要求右侧统计项必须是可调用的函数,直接传向量会触发长度校验错误

修改后可正常运行的完整代码如下:

library(modelsummary)
library(kableExtra)

tmp <- mtcars[, c("mpg", "hp")]

tmp$class <- 0
tmp$class[15:32] <- 1
tmp$class <- as.factor(tmp$class)

tmp$region <- 1
tmp$region[15:20] <- 2
tmp$region[21:32] <- 3
tmp$region <- as.factor(tmp$region)

N_alt = function(x) {
  if (x[1] %in% c(0,1)) { # class的取值为0、1
    paste0('[14 (43.8); 18 (56.3)]') 
  } else if (x[1] %in% c(1,2,3)) { # region的取值为1、2、3
    paste0('[14 (43.8); 6 (18.8); 12 (37.5)]')  
  } else {
    paste0('[32 (100)]')
  }
}

Mean_alt = function(x) {
  if ("mpg" %in% deparse(substitute(x))) {
    as.character(floor(mean(x)), length=5)
  } else if (is.factor(x)) {
    paste0("")
  } else {
    mean(x)
  }
}

datasummary(mpg + (`class [0,1]`= class) + (`region [A,B,C]`= region) + hp ~ Heading("N (%)") * N_alt + Heading("Mean") * Mean_alt, data = tmp)

内容的提问来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:15:04