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

使用flextable与tabulator按性别生成交叉表的问题求助

按性别生成交叉表的解决方案

问题说明

需基于给定数据按sex字段生成交叉表,后续将加入年龄变量;使用tabulator函数时触发错误:

Error in [.data.table(dat, , .SD, .SDcols = columns) :
Some items of .SDcols are not column names: [.tab_columns]

数据确认

先确保数据加载正确(修正dput格式后的代码):

df <- structure(
  list(
    country = c("SCO", "SCO", "SCO", "SCO", "SCO", "SCO", "WAL", "WAL", "WAL", "WAL", "WAL", "WAL"),
    sex = c("ALL", "M", "F", "ALL", "M", "F", "ALL", "M", "F", "ALL", "M", "F"),
    answer = c("A", "A", "A", "B", "B", "B", "A", "A", "A", "B", "B", "B"),
    value = c(50, 52, 48, 71, 77, 65, 45, 48, 43, 71, 79, 63)
  ),
  class = c("tbl_df", "tbl", "data.frame"),
  row.names = c(NA, -12L)
)

方案1:修复tabulator的使用

错误源于参数格式不符,且代码中数据对象名不匹配(你用了x=x,实际数据框是df)。修正后代码:

# 加载依赖包
library(flextable)
library(tables)

# 生成交叉表
tabulator(
  data = df,
  rows = ~ answer + country,
  columns = ~ sex,
  format = ~ value
) |> as_flextable()

方案2:使用你熟悉的crosstable函数

crosstable适配这类汇总场景,后续扩展年龄变量也很方便:

# 加载依赖包
library(crosstable)
library(flextable)

# 生成交叉表
crosstable(
  df,
  value,
  by = c(answer, country),  # 行维度
  col_by = sex,             # 列维度
  fun = identity            # 直接提取已有汇总值
) |> as_flextable()

后续添加年龄变量的扩展示例

假设数据新增age字段,只需调整分组参数:

crosstable(
  df_with_age,
  value,
  by = c(answer, country, age),  # 新增age到行维度
  col_by = sex,
  fun = identity
) |> as_flextable()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:37:18