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

如何将Stata中by分组tab命令生成的多表导出至LaTeX

解决Stata中按多分组导出交叉表到LaTeX的问题

方法1:用tabout生成分层交叉表

你之前的tabout没指定正确的分层逻辑,试试下面的命令,它会把state3作为外层分组,year作为内层,每个州下单独展示各年份的cooking_score分布:

tabout state3 year cooking_score using test1.tex, replace cells(freq col) ///
    h1("State: @state3") h2("Year: @year") ///
    ctitle("Frequency" "Column %") label tex
  • cells(freq col):输出频数和列百分比,要行百分比就换成row,总百分比用pct
  • h1/h2:给每个州、年份加上分组标题,让结构更清晰
  • label:用变量标签代替原始变量名,表格更易读

方法2:用esttab批量导出分组结果

如果习惯用esttab,得先把每个state3-year组合的交叉表单独存储,再合并导出:

* 清空已有估计结果
estimates clear

* 获取所有州和年份的取值
levelsof state3, local(states)
levelsof year, local(years)

* 循环生成每个分组的交叉表并存储
foreach s of local states {
    foreach y of local years {
        tab cooking_score if state3 == `s' & year == `y', matcell(freq) matrow(cs_vals)
        mat pct = freq / colsum(freq) * 100
        mat res = freq, pct
        estimates store cs_`s'_`y', matrix(res)
    }
}

* 导出到LaTeX
esttab cs_* using test2.tex, replace ///
    cells("b") collabels("Frequency" "Percent") ///
    nomtitle nonumber noobs label ///
    title("Cooking Score Distribution by State and Year") ///
    prehead("\begin{tabular}{lcc}" "\hline" "Cooking Score & Frequency & Percent \\" "\hline") ///
    posthead("\multicolumn{3}{c}{State: `s' | Year: `y'} \\" "\hline") ///
    postfoot("\hline" "\end{tabular}") tex

这段代码会遍历所有州和年份的组合,把每个组合的频数、百分比矩阵存起来,最后用esttab导出成带分层标题的LaTeX表格。

方法3:用tab2latex快速生成(需先安装)

如果没装tab2latex,先运行:

ssc install tab2latex

然后直接用分层导出命令:

by state3 year: tab cooking_score, matcell(tab_results)
tab2latex tab_results using test3.tex, replace ///
    rowlabels(cooking_score) collabels("Frequency") ///
    groupby(state3 year) label tex

这个命令会自动识别by分组的结构,直接生成符合你需求的分层LaTeX表格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:57:18